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


I have the following Node.js code:

var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());'/', function(request, response) {

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()?

6/24/2015 5:27:23 AM

Accepted Answer

Express 4.0 and above:

$ npm install --save body-parser

And then in your node app:

const bodyParser = require('body-parser');

Express 3.0 and below:

Try passing this in your cURL call:

--header "Content-Type: application/json"

and making sure your data is in JSON format:


Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:

var express = require('express');
var app = express.createServer();

app.use(express.bodyParser());'/', function(req, res){


This other question might also help: How to receive JSON in express node.js POST request?

If you don't want to use the bodyParser check out this other question:

7/24/2017 4:54:54 AM

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


Like this:

const express = require('express')

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

app.listen(8080)'/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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow