首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >express不像"api/:htip/feedback“那样处理url。

express不像"api/:htip/feedback“那样处理url。
EN

Stack Overflow用户
提问于 2014-01-21 16:55:45
回答 1查看 31关注 0票数 1

我正在使用nodejs和express创建一个web应用程序。我可以处理"/api/healthtips/:htip",代码如下:

代码语言:javascript
复制
app.get('/api/healthtips/:htip', function (req, res) {
return HealthTipModel.find({"_id": new mongoose.Types.ObjectId(req.params.htip)}, function (error, healthTip) {
    if (!error) {
        return res.send(healthTip);
    }
});

});

我在浏览器中签入,然后json返回。

但是我不能处理"api/:htip/feedback",有代码

代码语言:javascript
复制
app.post('api/:htip/feedback', function(req, res) {
var healthTip = HealthTipModel.find({"_id": new mongoose.Types.ObjectId(req.params.htip)}, function(error, healthTip) {
    if (!error) {
        return healthTip;
    }
});
if (healthTip._id) {
    var healthTip = new HTipFeedbackModel({
        type: req.body.type,
        comment: req.body.comment,
        healthTip: healthTip._id
    });
}

});

当我使用jquey.post访问此路径时,它返回404.

为什么?有人给我提示了吗?

EN

回答 1

Stack Overflow用户

发布于 2014-01-21 16:59:05

您不能只使用return,因为它是异步的。您应该使用回调:

代码语言:javascript
复制
app.post('/api/:htip/feedback', function(req, res) {

  HealthTipModel.findById(req.params.htip, function(error, healthTip) {

    if (!error) {

        var newhealthTip = new HTipFeedbackModel({
            type: req.body.type,
            comment: req.body.comment,
            healthTip: healthTip._id
        })

        newhealthTip.save(function(error){

          if (!error) {
             res.send(healthTip);
          } else {    
            res.status(400).send('Cannot save')
          }

        });   

    } else {    
      res.status(404).send('Not found')
    }
  });

});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21253324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档