2014-08-28 83 views
14

3年前我可以在express.js中做多个res.send。
甚至写一个setTimeout来显示一个实时输出。不能在express.js中做多个res.send

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表示已经更新。为什么现在不能这样做?任何其他想法?


找到的解决方案,但 “res.write” 不是API参考http://expressjs.com/4x/api.html ...

:S

回答

29

也许你需要:response.write

response.write("foo"); 
response.write("bar"); 
//... 
response.end() 

res.send隐含地呼叫res.write,然后是res.end。如果您多次致电res.send,它将首次运行。但是,由于第一个呼叫会结束响应,因此您无法向响应添加任何内容。

+0

是的,这听起来像这可能是他想到的。我完全忘记了Node的'response.write';我的大脑在快递地:/ – 2014-08-29 04:47:26

+2

很酷,这是我想要的。但是,为什么它不是在API参考http://expressjs.com/4x/api.html#res.send ??? – emj365 2014-08-29 08:07:34

+0

也许因为我们应该使用'res.render'或'res.send',当我是新手时,我使用'res.write'。 @ emj365为什么不尝试'res.render'? – osrpt 2014-08-29 11:41:59

11

response.send发送一个完整的HTTP响应于客户端,包括报头和内容,这就是为什么你无法多次调用它的原因。事实上,它甚至会结束响应,所以当使用response.send时,不需要明确地呼叫response.end

在我看来,你正在尝试使用send就像一个缓冲区:写入它的意图,以便稍后刷新。然而,这不是该方法的工作原理。您需要在代码中建立您的回复,然后拨打一个send电话。

不幸的是,我不能,为什么还是作出这一变化时说,但我知道,它一直是这样至少从快3

相关问题