node.js 为什么我们不能在 Express.js 中做多个 response.send?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25542521/
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
Why can't we do multiple response.send in Express.js?
提问by emj365
3 years ago I could do multiple res.send in express.js.
even write a setTimeout to show up a live output.
3 年前,我可以在 express.js 中执行多个 res.send。
甚至编写一个 setTimeout 来显示实时输出。
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>');
Now it will throw:
现在它会抛出:
Error: Can't set headers after they are sent
I know nodejs and express have updated. why can't do that now? any other idea?
我知道 nodejs 和 express 已经更新。为什么现在不能这样做?还有其他想法吗?
Found the solution but "res.write" is not in api reference http://expressjs.com/4x/api.html...
找到了解决方案,但“res.write”不在 api 参考http://expressjs.com/4x/api.html...
: S
:S
回答by yangsibai
Maybe you need: response.write
也许你需要: response.write
response.write("foo");
response.write("bar");
//...
response.end()
res.sendimplicitly calls res.writefollowed by res.end. If you call res.sendmultiple times, it will work the first time. However, since the first res.sendcall ends the response, you cannot add anything to the response.
res.send隐式调用res.write后跟res.end. 如果您res.send多次调用,它将在第一次起作用。但是,由于第一个res.send调用结束了响应,因此您不能向响应添加任何内容。
回答by Robert Mitchell
response.sendsends an entire HTTP response to the client, including headers and content, which is why you are unable to call it multiple times. In fact, it even ends the response, so there is no need to call response.endexplicitly when using response.send.
response.send向客户端发送完整的 HTTP 响应,包括标头和内容,这就是您无法多次调用它的原因。事实上,它甚至会结束响应,因此response.end在使用response.send.
It appears to me that you are attempting to use sendlike a buffer: writing to it with the intention to flush later. This is not how the method works, however; you need to build up your response in code and then make a single sendcall.
在我看来,您正试图send像缓冲区一样使用:写入它以便稍后刷新。然而,这不是该方法的工作方式。您需要在代码中构建您的响应,然后进行一次send调用。
Unfortunately, I cannot speak to why or when this change was made, but I know that it has been like this at least since Express 3.
不幸的是,我无法说明为什么或何时进行此更改,但我知道至少从 Express 3 开始就是这样。

