在node.js中发出HTTP请求并发送一个数据体
我目前正在通过Guillermo Rauchs“Smashing Node.Js”书。 我被困在第7章,其中的任务是build立一个客户端/服务器,并通过http连接从客户端发送一个string到服务器。 该string应该从服务器打印。
客户端代码:
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
根据这本书,这里也应该是一个“笨蛋”。
, method: 'GET'
应该
, method: 'POST'
GET请求没有主体,所以在服务器端没有任何东西需要parsing。