node.js-我无法从服务器复制渐进响应 [英] node.js - i can't reproduce progressive response from server

查看:44
本文介绍了node.js-我无法从服务器复制渐进响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧

我对node.js完全陌生.我开始尝试Ryan Dahl( http://www.youtube.com/watch?v = jo_B4LTHi3I )在这一点上(大约0:17:00),有一个关于服务器如何处理响应的解释,

i'm completely new to node.js. Starting to try it, i'm following the introduction made by Ryan Dahl (http://www.youtube.com/watch?v=jo_B4LTHi3I) and at this point (around 0:17:00) there's an explanation about how server handles responses,

基本示例是从网络服务器获得"hello"输出,然后在2秒钟后出现"world",此代码应该可以做到这一点

The basic example is to have a 'hello' output from webserver and then after 2 secs it comes the 'world', this code is supposed to do that

//Require the webserver library 
var http = require('http');

var server = http.createServer(function(req, res) {
    res.writeHead(200, { 'content-type' : 'text-plain' });
    res.write('Hello\n');

    //Asynchronous behavior
    setTimeout(function() {
        res.end('World\n');
    }, 2000);
});

server.listen(3000);

所以我运行它,我得到了Hello World,但是只有一个完整的结果来自服务器,即请求> 2秒>'Hello World'.而不是请求> Hello> 2 secs> World.

So i run it, and i get the Hello World but there's only one response from server with the complete result, that is, request > 2 sec > 'Hello World'. Instead of request > Hello > 2 secs > World.

为什么?,如何更改此行为?

我正在使用v0.8.18,curl -i http://localhost:3000 返回正确的标题... HTTP/1.1 200确定内容类型:纯文本日期:2013年1月26日,星期六,格林尼治标准时间连接:保持活动状态传输编码:分块

I'm using v0.8.18, curl -i http://localhost:3000 returns the right headers... HTTP/1.1 200 OK content-type: text-plain Date: Sat, 26 Jan 2013 18:10:05 GMT Connection: keep-alive Transfer-Encoding: chunked

推荐答案

在开始渲染之前,它是浏览器会缓冲传入的数据,直到收到一定数量的数据为止.您的Node代码按预期运行,它将发送响应的第一部分,然后等待2秒钟,然后发送后半部分.

It is the browser that buffers the incoming data until some amount has been received, before starting to render. Your Node code does just as you expect, it will sent the first part of the response, then wait for 2 seconds, then send the second half.

如果要观察此行为,可以发送一堆空格以使浏览器清空其缓冲区.如果您是在初次写入后添加此代码,则会看到浏览器呈现请求的前半部分.

If you want to observe this behavior, you can send a bunch of spaces to make the browser empty its buffer. If you add this after your initial write, you will see the browser render the first half of the request.

var str = '';
for (var i = 0; i < 2000; i++){
  str += ' ';
}
res.write(str);

显然不要在真实代码中执行此操作,但是很好地演示这种行为.

Obviously don't do this in real code, but it's good to demonstrate the behavior.

这篇关于node.js-我无法从服务器复制渐进响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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