【问题标题】:Mean.js Query var not workingMean.js 查询变量不起作用
【发布时间】:2016-10-05 21:15:03
【问题描述】:

我使用 Mean.js 创建一个博客,我用 npm 安装它,我创建 crud 模块评论来评论每篇文章,我用article id 保存一些评论作为参考。我在服务器中创建 api 路由。

  // Comments Routes
 app.route('/api/comments/:articleId').all()
    .get(comments.listbyArticle);

在服务器控制器上

    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

它响应除此文章 ID 之外的所有 cmets,如果我硬编码 ('57550c21612bc90478333017') 文章 ID 而不是 req.articleId。然后响应显示我正确的 cmets。

请解释一下有什么问题?

【问题讨论】:

  • req.articleId 的值正确出现?
  • 不,它没有正常运行,我认为 req.articleId 为空或 null,我如何检查 req 里面的内容?我尝试用响应返回 req 但是当我做路由中断时。

标签: javascript angularjs node.js mongodb mean-stack


【解决方案1】:

您应该使用 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);
                }
            });
};

【讨论】:

    猜你喜欢
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多