我正在使用 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/