我使用 Mean.js 创建博客,我使用 npm 安装它,并创建 CRUD 模块注释来评论每篇文章,并使用 article
id 保存一些评论作为引用。我在服务器中创建 api 路由。
// Comments Routes
app.route('/api/comments/:articleId').all()
.get(comments.listbyArticle);
在服务器 Controller 上
exports.listbyArticle = function(req, res) {
Comment.find( {article : req.articleId }).sort('-created').populate('user', 'displayName').exec(function(err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
但是当导航到这条路线时
http://localhost:3000/api/comments/57550c21612bc90478333017
如果我硬编码('57550c21612bc90478333017'
)文章ID而不是req.articleId
,它会响应除本文ID之外的所有评论。然后响应会向我显示正确的评论.
请解释一下哪里出了问题?
最佳答案
您应该使用 req.params
访问URL中的articleId:
exports.listbyArticle = function(req, res) {
var articleId = req.params.articleId;
Comment.find( {article: articleId }).sort('-created')
.populate('user', 'displayName')
.exec(function(err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
关于javascript - Mean.js 查询变量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37654450/