How to access the request body when POSTing using Node.js and Express?

TheBlueSky picture TheBlueSky · Jul 24, 2012 · Viewed 368.5k times · Source

I have the following Node.js code:

var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());

app.post('/', function(request, response) {
    response.write(request.body.user);
    response.end();
});

Now if I POST something like:

curl -d user=Someone -H Accept:application/json --url http://localhost:5000

I get Someone as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body) but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body; and then writing response.write(reqBody).

What's the issue here?

Also, can I just get the raw request without using express.bodyParser()?

Answer

rustyx picture rustyx · Apr 20, 2018

Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:

app.use(express.json())

Like this:

const express = require('express')

app.use(express.json())    // <==== parse request body as JSON

app.listen(8080)

app.post('/test', (req, res) => {
  res.json({requestBody: req.body})  // <==== req.body will be a parsed JSON object
})

Note - body-parser, on which this depends, is already included with express.

Also don't forget to send the header Content-Type: application/json