在 nodejs 中发布后重定向错误 'Can't 在发送标头后设置标头' [英] Redirect after posting in nodejs Error 'Can't set headers after they are sent'
本文介绍了在 nodejs 中发布后重定向错误 'Can't 在发送标头后设置标头'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在nodejs中发布后重定向错误发送后无法设置标头"这是代码
Redirect after posting in nodejs Error 'Can't set headers after they are sent' Here is code
router.post('/newItem', function (req, res, next) {
product.insertItem(req.body, req.files, function (err ,result) {
if (err) throw err;
res.redirect(307, '/home');
});
});
这是模块insertItem函数
This is module insertItem function
module.exports.insertItem = function (doc, file, callback) {
mongo.item.insert(data, function (err, result) {
if (err) throw err;
callback(err, result);
});
})
这总是在下面抛出错误
/Users/hello/Desktop/dev/project/node_modules/mongodb/lib/utils.js:95
process.nextTick(function() { throw err; });
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
at ServerResponse.header (/Users/hello/Desktop/dev/project/node_modules/express/lib/response.js:564:10)
at ServerResponse.res.location (/Users/hello/Desktop/dev/project/node_modules/express/lib/response.js:678:8)
at ServerResponse.redirect
我该如何解决问题..?
How can I solve the problem..?
推荐答案
当我在有问题的块之后有更多代码时,我遇到了与 res.redirect
类似的问题.
I ran into a similar problem with res.redirect
when I had more code after the block in question.
我在重定向后用 return false
解决了这个问题.
I solved it with return false
after the redirect.
在您的情况下,它看起来像这样:
In your case it would look like this:
res.redirect(307, '/home');返回假;
这篇关于在 nodejs 中发布后重定向错误 'Can't 在发送标头后设置标头'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文