I'm currently going through Guillermo Rauchs "Smashing Node.Js" Book. I'm stuck in chapter 7 where the task is to set up a client/server and to send a string from the client to the server over a http connection. The string should be printed from the server.
the client code:
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', ''));
});
the server:
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);
I start the client and the server. The client seems to work:
mles@se31:~/nodejs/tweet-client$ node client.js
your name: mles
request complete!
your name:
However on the server side, it's only showing an undefined:
mles@se31:~/nodejs/tweet-client$ node server.js
got name undefined
According to the book, here should be an "mles" too.
, method: 'GET'
should be
, method: 'POST'
GET requests do not have a body so there is nothing to parse on the server's side.