SimCor
SimCor

Reputation: 300

Reading requests body Nodejs

I'm running this simple http node.js server:

var http = require('http');

http.createServer(function (req, res) {

}).listen(6000);

Can you explain me, how I can read the body of the incoming requests, in orderd to visualize it on the console?

Upvotes: 1

Views: 692

Answers (1)

rsp
rsp

Reputation: 111278

You could pipe the request stream to stdout:

var http = require('http');

http.createServer(function (req, res) {
  req.pipe(process.stdout);
}).listen(6000);

Update: If the body contains JSON and you want to deserialize it then you could build up a string from the stream data chunks and use JSON.parse() on that (remembering to put it in a try/catch block or using tryjson) or you could use a tested solution for that - because if you want to parse the JSON body then I suspect that you may need to do more with that.

Example with Express and body-parser:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use((req, res) => {
  // req.body is deserialized body:
  console.log(req.body);
});    
app.listen(6000);

or with an older syntax:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(function (req, res) {
  // req.body is deserialized body:
  console.log(req.body);
});    
app.listen(6000);

You can test it with curl like this:

curl -X POST -H 'Content-type: application/json' -d '{"a":1,"b":2}' localhost:6000

It prints:

{ a: 1, b: 2 }

and you can see it's parsed by the lack of quotes around the object keys.

Of course you can use things like req.body.someArray[3] etc. - it's fully parsed and usable.

Upvotes: 2

Related Questions