为什么我们不能在Express.js中执行多个response.send? [英] Why can't we do multiple response.send in Express.js?

查看:281
本文介绍了为什么我们不能在Express.js中执行多个response.send?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?

找到了解决方案,但是api参考中没有"res.write" 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆