不能在express.js中做多个res.send

emj*_*365 27 node.js express

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>');
Run Code Online (Sandbox Code Playgroud)

现在它将抛出:

Error: Can't set headers after they are sent
Run Code Online (Sandbox Code Playgroud)

我知道nodejs和express已更新.为什么现在不能这样做?还有其他想法吗?


找到解决方案,但"res.write"不在api参考http://expressjs.com/4x/api.html ...

:S

yan*_*bai 48

也许你需要: response.write

response.write("foo");
response.write("bar");
//...
response.end()
Run Code Online (Sandbox Code Playgroud)

res.send隐式调用res.write后跟res.end.如果你res.send多次打电话,它将第一次工作.但是,由于第一个res.send调用结束响应,因此无法向响应添加任何内容.

  • `respone.write`和`response.writeHead`来自`http.ServerResponse` api [node doc](http://nodejs.org/api/http.html#http_response_write_chunk_encoding) (3认同)
  • 很酷,这是我想要的.但是,为什么它不在api参考http://expressjs.com/4x/api.html#res.send ??? (2认同)

Rob*_*ell 15

response.send向客户端发送完整的HTTP响应,包括标头和内容,这就是您无法多次调用它的原因.实际上,它甚至会结束响应,因此response.end在使用时无需显式调用response.send.

在我看来,你试图send像缓冲区一样使用:写入它以便稍后刷新.然而,这不是该方法的工作方式; 你需要在代码中建立你的响应,然后进行一次send调用.

不幸的是,我不能说出为什么或何时做出这种改变,但我知道至少从Express 3开始就是这样.