【问题标题】:Making HTTP requests and sending a body of data in node.js在 node.js 中发出 HTTP 请求并发送数据体
【发布时间】:2013-02-03 01:12:28
【问题描述】:

我目前正在阅读 Guillermo Rauchs “Smashing Node.Js”一书。我被困在第 7 章,任务是设置客户端/服务器并通过 http 连接从客户端向服务器发送字符串。字符串应该从服务器打印出来。

客户端代码:

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

function send (theName) {
    http.request({
        host: '127.0.0.1'
        , port: 3000
        , url: '/'
        , method: 'GET'
    }, function (res) {
        res.setEncoding('utf-8');
        res.on('end', function () {
            console.log('\n   \033[090m 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', ''));
});

服务器:

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

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);

我启动客户端和服务器。客户端似乎工作:

mles@se31:~/nodejs/tweet-client$ node client.js 

your name:  mles

   request complete!

your name:  

但是在服务器端,它只显示一个未定义的:

mles@se31:~/nodejs/tweet-client$ node server.js 

got name undefined

按照书上的说法,这里也应该有一个“mles”。

【问题讨论】:

    标签: javascript node.js http client-server


    【解决方案1】:
    , method: 'GET'
    

    应该是

    , method: 'POST'
    

    GET 请求没有正文,因此在服务器端没有要解析的内容。

    【讨论】:

    • 这里的规范有点模糊,但我认为你在那个节点中是对的,不允许带有 GET 的主体。
    • @Joe 确实如此。我不知道是客户端不使用GET发送数据,还是服务器忽略了GET数据,但使用POST肯定可以解决它。
    • 是的。在这种情况下甚至不会触发 on('data') 事件。
    猜你喜欢
    • 2012-03-27
    • 2021-08-18
    • 2014-02-14
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    • 2023-03-24
    • 2021-12-17
    • 1970-01-01
    相关资源
    最近更新 更多