Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get url and body from IncomingMessage?

Tags:

http

node.js

I am very new to node. I am at the point at which I have a simple server which should just print the request query and the request body which it takes. What I've understood is that the "handle request" function actually doesn't return a request object, rather an IncomingMessage object.

There are two things which I don't understand: How to obtain the query string and the body.

I get just the path, without the query and undefined for the body.

Server Code:

var http = require('http');

var server = http.createServer(function (request, response) {
  console.log("Request query  " + request.url);
  console.log("Request body  " + request.body);
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("<h1>Hello world!</h1>");
});

server.listen(8000);

console.log("Server running at http://127.0.0.1:8000/");

Request code:

var http = require('http');

var options = {
  host: '127.0.0.1',
  port: 8000,
  path: '/',
  query: "argument=narnia",
  method: 'GET'
};

var req = http.request(options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('response: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

req.write("<h1>Hello!</h1>");
req.end();

Please note that I am a complete beginner. I am not looking for express only solutions.

like image 389
Stanimirovv Avatar asked Jul 06 '14 19:07

Stanimirovv


Video Answer


1 Answers

The reason that you do not see the query string at request.url is that you aren't sending one correctly. In your request code, there is no query property of options. You must append your querystring to the path.

path: '/' + '?' +  querystring.stringify({argument: 'narnia'}),

For your second question, if you want the full request body, you must read from the request object like a stream.

var server = http.createServer(function (request, response) {
  request.on('data', function (chunk) {
    // Do something with `chunk` here
  });
});
like image 79
Brad Avatar answered Oct 07 '22 20:10

Brad