Pindakaas
Pindakaas

Reputation: 4439

How can I get the body of the postrequest in nodejs?

I am getting my head around node.js and trying to construct a post request, this is my server.js file:

module.exports = function(app) {
    app.post('/api/postrequest', function(req, res) {
        console.log('inside postrequest');
        console.log(req.body); //this is empty????
        });

    // application -------------------------------------------------------------
    app.get('*', function(req, res) {
        res.sendfile('./public/index.html'); // load the single view file (angular will handle the page changes on the front-end)
    });
};

I would like to filter data from the request so try to verify what is in req.body. The problem is it is empty : {}. To test I am using Postman to submit the request:

http://localhost:8080/api/postrequest

Using the raw format to post this json:

{"name":"Eddie"}

Upvotes: 0

Views: 45

Answers (1)

Bidhan
Bidhan

Reputation: 10687

You will need to use a middleware like body-parser to do that. Do an npm install body-parser and require it in your app with

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

Then use it like so

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended': 'true'}));

Upvotes: 1

Related Questions