Search code examples
javascriptnode.jsexpress

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

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


Solution

  • Express 4.0 and above:

    $ npm install --save body-parser

    And then in your node app:

    const bodyParser = require('body-parser');
    app.use(bodyParser);
    

    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:

    {"user":"someone"}

    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());
    
    app.post('/', function(req, res){
        console.dir(req.body);
        res.send("test");
    }); 
    
    app.listen(3000);
    

    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: https://stackoverflow.com/a/9920700/446681