javascript 在快递上发送后无法设置标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27658997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't set headers after they are sent on express
提问by Munkhbat Mygmarsuren
I khow like a common question here on. But I couldn't get a solution from everywhere. here is my code: if row is not empty then render code page, otherwise perform another action.
我知道这里有一个常见问题。但我无法从任何地方得到解决方案。这是我的代码:如果行不为空,则呈现代码页,否则执行另一个操作。
app.get('/send',function(req,res){
var code=req.query['c']; // -- get request from input
connection.query("use mynum");
var strQuery = "select * from table WHERE code='"+code+"' LIMIT 1";
connection.query( strQuery, function(err, rows){
if(err) {
throw err;
}else{
if(rows.length==1){
res.render('pages/code', {code : rows[0].code});
connection.end();
res.end();
}else {
// here is some actions
}
}
});
res.end();
});
the stack trace:
堆栈跟踪:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:690:11)
at ServerResponse.header (C:\wamp\www\vin_number\node_modules\express\lib\re
sponse.js:666:10)
at ServerResponse.res.contentType.res.type (C:\wamp\www\vin_number\node_modu
les\express\lib\response.js:532:15)
at ServerResponse.send (C:\wamp\www\vin_number\node_modules\express\lib\resp
onse.js:121:14)
at fn (C:\wamp\www\vin_number\node_modules\express\lib\response.js:900:10)
at View.exports.renderFile [as engine] (C:\wamp\www\vin_number\node_modules\
ejs\lib\ejs.js:323:3)
at View.render (C:\wamp\www\vin_number\node_modules\express\lib\view.js:93:8
)
at EventEmitter.app.render (C:\wamp\www\vin_number\node_modules\express\lib\
application.js:530:10)
at ServerResponse.res.render (C:\wamp\www\vin_number\node_modules\express\li
b\response.js:904:7)
at Query._callback (C:\wamp\www\vin_number\server.js:102:6)
回答by mscdex
You're sending a response twice via res.end()
. Get rid of the second one and you should be fine. Also, calling res.end()
after res.render()
is redundant since res.render()
automatically ends the response with the rendered result by default.
您通过 发送了两次响应res.end()
。摆脱第二个,你应该没问题。此外,调用res.end()
afterres.render()
是多余的,因为res.render()
默认情况下会自动以呈现的结果结束响应。
回答by Adam Boostani
Just learned this! pass your responses through a function that checks if the response was already sent:
刚学这个!通过检查响应是否已发送的函数传递您的响应:
app.use(function(req,res,next){
var _send = res.send;
var sent = false;
res.send = function(data){
if(sent) return;
_send.bind(res)(data);
sent = true;
};
next();
});