2

我目前正在阅读 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”。

4

1 回答 1

3
, method: 'GET'

should be

, method: 'POST'

GET requests do not have a body so there is nothing to parse on the server's side.

于 2013-02-03T01:41:26.960 回答