Thursday 20 April 2017

Unable to read body in post response [express.js]

I am making a post request using Restlet client tool in chrome. In console.log(res), I can clearly see that there is body present there with totally correct data but still I am always getting an error message saying body is undefined when doing res.body.

Here is the code

var express = require('express');
var parser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

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

var db = mongoose.connection;

var port = process.env.PORT || 8000;

var router = express.Router();

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next(); // make sure we go to the next routes and don't stop here
});

router.get('/',function(req,res){
    res.json({msg: 'Welcome to Pre-Health API!'});
}); 

var User = mongoose.Schema({
        first_name: String,
        last_name: String
    },{
        collection: 'User',
        timestamps: true
    });

router.route('/user').post(function(res,req) {
    var user = mongoose.model('user',User);
    console.log(req);
    var new_user = new user({
       first_name: req.body.first_name,
       last_name: req.body.last_name
    });

    user.save(function(err) {
        if(err) res.send(err);
        res.json({message: "User created"});
    });
});

app.use('/api',router);

app.listen(port);
console.log('API Listening on port: ' + port);



via Mohit Bhatia

No comments:

Post a Comment