2

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.

1 Answer 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.

Sign up to request clarification or add additional context in comments.

3 Comments

The spec is kind of vague here, but I think you're right in that node does not allow a body with a GET.
@Joe True enough. I don't know if it's the client that doesn't send data with GET, or the server that ignores data for GET, but using POST definitely fixes it.
Yep. No on('data') events even fire in that case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.