Reputation: 69
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);
Upvotes: 1
Views: 456
Reputation:
In the function you have req
and res
inverted, it should be:
router.route('/user').post(function(req, res) { ...
Upvotes: 2