Node Js problems with response.write

半世苍凉 提交于 2019-11-26 22:59:11

问题


When I try to utilize http stream connection for some reason write does not flush until I call response.end()
I am taking the code straight from the demo and do not understand what my problem is.
When I curl to the server my headers are correct.

HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked


var http = require('http');
    http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.write('hello');
      res.write(':');
      setTimeout(function(){ 
          res.end('World\n')},
          2000);
    }).listen(1337, "127.0.0.1");
    console.log('Server running at http://127.0.0.1:1337/');

Why is the server not sending the write data?


回答1:


I seems to be browser specific behavior -- firefox shows the data ("Hello:") immediately while chrome seems to buffer and wait until the response is ended. Note that chrome also shows the data immediately if you write more data at first (e.g. I wrote 1000 "Hello"s).




回答2:


I think I understand what you mean...

From the node.js docs:

The first time response.write() is called, it will send the buffered header information and the first body to the client. The second time response.write() is called, Node assumes you're going to be streaming data, and sends that separately. That is, the response is buffered up to the first chunk of body.

http://nodejs.org/docs/v0.4.7/api/all.html#response.write

(Nice port usage BTW :) )




回答3:


Try to check your code with telnet or nc. curl usually buffers last line




回答4:


After fixing the missing curly brace, your code is working for me from a browser. Curl from the commandline seems to wait for the full response but wireshark confirms that it does use chunked encoding and the response was split into 2 packages in both cases.

I assume that the curl output is line buffered and waiting for the newline after 'World' before it prints anything. You can confirm this by printing another newline after 'hello:'.




回答5:


this is due to you missed a enclosing "}" in your code at position after res.end('World\n') and before the comma.



来源:https://stackoverflow.com/questions/6068820/node-js-problems-with-response-write

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!