javascript - nodejs用http模块写的简单程序,服务器端获取客户端发送名字发生的问题,为何此处代码没有运行到,求解答?
ringa_lee
ringa_lee 2017-04-11 11:53:28
[JavaScript讨论组]

代码运行后,第一次客户端上有显示your name: ,第一次之后再输其它名字时都没有显示your name: ,但是服务器端可以正常显示从客户端得到的名字。

以下是server.js代码

var qs = require('querystring');

require('http').createServer(function (req, res) {
    var body = '';
    req.on('data', function (chunk) {
        body += chunk;
    });
    req.on('end', function () {
        res.writeHead(200);
        res.end('Done');
        console.log('\n  got name \033[90m' + qs.parse(body).name + '\033[39m\n');
    });
}).listen(3000);

以下是client.js代码

var http = require('http'), qs = require('querystring');

function send (theName) {
    http.request({ host: '127.0.0.1', port: 3000, url: '/', method: 'POST' }, function (res) {
        res.setEncoding('utf8');
        res.on('end', function () {
            console.log('\n  \033[90m✔ request complete!\033[39m');
            process.stdout.write('\n  your name: ');
        });
    }).end(qs.stringify({ name: theName }));
}

process.stdout.write('\n  your name: ');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function (name) {
    send(name.replace('\n', ''));
});

截图左边是server,右边是client。
我试着把client的这段代码删掉,结果似乎仍不影响正常运行。

res.on('end', function () {
            console.log('\n  \033[90m✔ request complete!\033[39m');
            process.stdout.write('\n  your name: ');
        });

为什么这段代码没有运行到呢?

ringa_lee
ringa_lee

ringa_lee

全部回复(2)
大家讲道理

HTTP responses, on the client是一个Readable Streams,它的end事件只有在数据全部被consumed的时候才会触发. 在你的client.js修改send函数,添加res.on('data',...)处理, 如果你对数据不care,也可以使用res.resume()。 你自己选一个吧!

function send (theName) {
    http.request({ host: '127.0.0.1', port: 3000, url: '/', method: 'POST' }, function (res) {
        res.setEncoding('utf8');
        // consume the data
        res.on('data', (chunk) => {
          console.log(`BODY: ${chunk}`);
        });
        // if you don't care the data using the next code 
        // res.resume();
        res.on('end', function () {
            console.log('\n  \033[90m✔ request complete!\033[39m');
            process.stdout.write('\n  your name: ');
        });
    }).end(qs.stringify({ name: theName }));
}

Note: The 'end' event will not be emitted unless the data is completely consumed. This can be accomplished by switching the stream into flowing mode, or by calling stream.read() repeatedly until all data has been consumed.

  • See More

巴扎黑

end检测的是data事件结束的的,所以你要表明data事件才可以的。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号