TheBlueSky TheBlueSky - 1 year ago 80
Javascript Question

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
as expected. Now, what if I want to get the full request body? I tried doing
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

What's the issue here?

Also, can I just get the raw request without using

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download