Get url and body from IncomingMessage?

I am very new to node. I am at the point where I have a simple server that should just print the request and the body request that it accepts. I realized that the request request function does not actually return a request object, not an IncomingMessage object.

There are two things that I don’t understand: how to get the query string and body.

I only get the path, no request 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 newbie. I am not looking only for express solutions.

+7
source share
1 answer

The reason you don't see the query string in request.url is because you are not sending it correctly. Your query code does not have the query property options . You must add your chain to path .

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

For your second question, if you want to get the full request, you should read from the request object as a stream.

 var server = http.createServer(function (request, response) { request.on('data', function (chunk) { // Do something with `chunk` here }); }); 
+4
source share

All Articles