这是您可以解释但不知道如何修复它的问题之一。我有一个简单的store
方法:
exports.store = async (req, res) => {
const mydata = new MyModel(req.body)
await mydata.save(function(err,user) {
res.location('/mydata/id/' + user._id)
})
res.status(201).json({ data: userdata })
}
运行时,我收到以下错误:
events.js:182
throw er; // Unhandled 'error' event
^
Error: Can't set headers after they are sent.
at validateHeader (_http_outgoing.js:489:11)
at ServerResponse.setHeader (_http_outgoing.js:496:3)
at ServerResponse.header (.../node_modules/express/lib/response.js:730:10)
at ServerResponse.location (.../node_modules/express/lib/response.js:847:15)
at .../src/controllers/users-controller.js:26:13
at .../node_modules/mongoose/lib/model.js:3919:16
at .../node_modules/mongoose/lib/services/model/applyHooks.js:162:20
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
Process finished with exit code 1
我看来回调函数是单独和异步运行的,因为res.status(201).json({ data: userdata })
似乎产生错误并且不允许我设置位置标题。
我已经四处寻找如何设置位置标题,但没有一个答案就像我想要做的那样。这似乎是应该在......之前完成的事情?我正在寻找一些如何做到这一点的帮助...
答案 0 :(得分:1)
你混淆了两种思维方式:
只使用一个
try {
const user = await mydata.save();
res.location(`/mydata/id/${user._id}`);
// Other stuff ...
} catch(err) {
// Handle the errors
}
https://github.com/rollup/rollup-plugin-replace#usage你得到一篇关于Promises到mongoose的文章。