Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

252
Views
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);
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In the function you have req and res inverted, it should be:

router.route('/user').post(function(req, res) { ...
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!