Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

250
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda