3 回答

TA贡献1880条经验 获得超4个赞
你得到的错误是因为代码行
res.status(200).json({
message: 'Team successfully created',
team: team
});
无论是否出错,都会被调用。如果出现错误,则 express 已经在此代码中发送了响应标头
if (err) {
res.status(400).send(err);
}
所以当 express 尝试下面的代码时,它会得到你表达的错误。答案是使用 Rami Jarrar 提供的答案
// save the team and check for errors
team.save(function (err) {
if (err) {
res.status(400).send(err);
}
res.status(200).json({
message: 'Team successfully created',
team: team
});
});

TA贡献1805条经验 获得超9个赞
您关于res.send()破坏的假设是不正确的,只有当您return. 调用return上res.send()的错误,使其不继续的情况下。如果你得到一个错误,它会将状态设置为 400(在标题中),然后是正文中的错误,但是因为它没有返回它然后尝试将状态设置为 200(在标题中)导致你的错误看到。
// save the team and check for errors
team.save(function (err) {
if (err) {
// return here so that it will not continue!
return res.status(400).send(err);
}
// return here if there is no error!
return res.status(200).json({
message: 'Team successfully created',
team: team
});
});
Express 将中间件链接在一起使用function(req, res, next),并且可以通过res.send()多个中间件返回结果。链中的下一个中间件在您调用时调用return next(),因此,例如,如果您想在成功时返回另一个中间件中的附加数据,则不会return res.send()而是return next()在res.send().
添加回答
举报