我正在使用 The Movie Database 为我的投资组合构建一个简单的应用程序API。在我的 GET/movie 路由中,我想要获取并显示有关电影的数据以及 Actor 的姓名和照片,但是电影的数据和 Actor 的数据属于 api 的两个单独的端点,我完全不知道如何在我的应用程序中的单个端点下访问两个响应数据集。
我无法在/movie 路由下的两个端点上调用 axios.get(),因为我会收到“ header 已发送”错误,并且我尝试编写一个使用 axios.get 作为 1 个端点的函数,该函数返回响应并在我的 GET/movie 路由中被调用,但这会导致整个 GET 路由返回未定义。
这是我当前的/movie 路线代码,该代码不正确,但密切传达了我想要完成的任务
const express = require('express');
const router = express.Router();
const axios = require('axios');
const api_key = require('../config/keys').api_key;
const imgURL = "http://image.tmdb.org/t/p/";
const dateFormat = require('../config/dateFormat');
getActors = movie_id => {
axios.get(`https://api.themoviedb.org/3/movie/${movie_id}/credits?api_key=${api_key}&language=en-US`)
.then(res => {
return res.data;
}).catch(err => console.log(err.message));
}
router.get('/:id', (req, res) => {
const id = req.params.id
axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=${api_key}&language=en-US`)
.then(res => {
const movieData = res.data;
const actors = getActors(id); //calling above function here, but returns undefined and hangs the application
res.render('movie', {movieInfo: movieData, imgURL: imgURL, releaseDate: dateFormat(movieData.release_date), actors: actors})
})
.catch(err => console.log(err.status_message))
});
module.exports = router;
非常感谢任何帮助。
最佳答案
您可以使用 axios.all 连接多个 Promise 并并行执行它们。然后,一旦完成所有添加的请求,您就可以使用 then Promise 处理所有请求的结果。例如,在您的代码中:
const express = require('express');
const router = express.Router();
const axios = require('axios');
const api_key = require('../config/keys').api_key;
const imgURL = "http://image.tmdb.org/t/p/";
const dateFormat = require('../config/dateFormat');
axios.all([
axios.get(`https://api.themoviedb.org/3/movie/${movie_id}/credits?api_key=${api_key}&language=en-US`),
axios.get(`https://api.themoviedb.org/3/movie/${id}?api_key=${api_key}&language=en-US`)
])
.then(axios.spread((actorsRes, moviesRes) => {
// Your logic with each response
});
module.exports = router;
关于javascript - 如何同时调用两个不同的 REST api 端点并在应用程序的一个端点上显示来自这两个端点的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54337146/