为什么我们不能在 Express.js 中做多个 response.send? [英] Why can't we do multiple response.send in Express.js?
问题描述
3 年前,我可以在 express.js 中执行多个 res.send.
甚至编写一个 setTimeout 来显示实时输出.
3 years ago I could do multiple res.send in express.js.
even write a setTimeout to show up a live output.
response.send('<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>');
response.send('<html><body><input id="text_box" /><button>submit</button></body></html>');
var initJs = function() {
$('.button').click(function() {
$.post('/input', { input: $('#text_box').val() }, function() { alert('has send');});
});
}
response.send('<script>' + initJs + '</script>');
现在它会抛出:
Error: Can't set headers after they are sent
我知道 nodejs 和 express 已经更新.为什么现在不能这样做?还有其他想法吗?
I know nodejs and express have updated. why can't do that now? any other idea?
找到解决方案,但res.write"不在 api 参考中 http://expressjs.com/4x/api.html ...
Found the solution but "res.write" is not in api reference http://expressjs.com/4x/api.html ...
:S
推荐答案
也许你需要:response.write
response.write("foo");
response.write("bar");
//...
response.end()
res.send
隐式调用 res.write
后跟 res.end
.如果多次调用 res.send
,它会在第一次工作.但是,由于第一个 res.send
调用结束了响应,因此您不能向响应添加任何内容.
res.send
implicitly calls res.write
followed by res.end
. If you call res.send
multiple times, it will work the first time. However, since the first res.send
call ends the response, you cannot add anything to the response.
这篇关于为什么我们不能在 Express.js 中做多个 response.send?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!