简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM