我正在使用Express创建一个端点,以根据电影ID返回评论或从电影中查看。正如您在第一个路径中看到的那样,手动传递ID,并返回来自TheMovieDB的数据。我不想对ID进行硬编码,因此我尝试在第二条路径中使其动态化。
预先填写:
app.get('/comments/', (req, res) => {
request('https://api.themoviedb.org/3/movie/401478/reviews?api_key={key}', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred and handle it
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.send(body)
});
});
动态:
app.get('/comments/:id', (req, res) => {
const id = req.params.id;
request('https://api.themoviedb.org/3/movie/' + id +'/reviews?api_key={key}', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred and handle it
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
res.send(body)
});
});
当我使用预先填写的方法并请求时:
localhost:8000/comments/
我得到了正确的答复(评论+评论)
当我像这样使用动态路线时:
localhost:8000/comments/351286
我收到以下回复:{"status_code":34,"status_message":"The resource you requested could not be found."}
我的代码出了什么问题?
答案 0 :(得分:0)
可以找到错误列表here。 您应该通过以下方式处理请求:
app.get('/comments/:id', (req, res) => {
const {id} = req.params;
request('https://api.themoviedb.org/3/movie/' + id +'/reviews?api_key={key}', function (error, response, body) {
if (error) return error;
if (!reponse) res.send("No themoviedb API response!");
else {
swicth (response.statusCode) {
case 200:
res.send(body);
break;
case 501:
res.send("Invalid service: this service does not exist");
breal;
//more status codes...
default:
res.send("Generic error");
}
}
});
});