node.js - Express 不处理这样的 url "api/:htip/feedback"

标签 node.js express

我正在使用 Nodejs 和 Express 创建一个 Web 应用程序。 我可以处理“/api/healthtips/:htip”,代码如下:

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”

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。

为什么?有人给我线索吗?

最佳答案

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

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')
    }
  });

});

关于node.js - Express 不处理这样的 url "api/:htip/feedback",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21253324/

相关文章:

javascript - Nodejs Mysql回调中的回调

node.js - 在 2 条路线 express 之间共享一个变量

node.js - Mongo/Mongoose 检查项目是否存在

node.js - Next.js api 无服务器函数上的 express' res.sendStatus(200) 等效于什么?

node.js - sequelize beforeValidate 将键和值放入对象

node.js - 如何使用同一 Twitter 应用程序对来自一个域的多个主机名进行 Twitter 身份验证?

node.js - nodeJS-Express 或 Meteor 或 Derby

node.js - 无法运行 node.js 示例

javascript - 如何使用node.js从mySQL读取数据并回传到HTML?

reactjs - 处理 axios React-Redux 应用程序中的 401 未经授权错误