user3583158
user3583158

Reputation: 3

Request body is empty in Express route

I am building an API with Node.js, Express.js, and MongoDB. When I submit the form and use the req object in the route, the req.body object is empty.

req.body returns {} when I call the get_user function through the browser using postman at https://localhost:3000/users/0.

app.js:

var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000,
    bodyParser = require('body-parser');

var mongo_server = require('./server')

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

var routes = require('./routes/users')
routes(app);

app.use(function(req, res) { 
    res.status(404).send({url: req.originalUrl + ' not found'});
});

app.listen(port);

mongo_server.mongo_connection

module.exports = app;

userController.js:

var mongoose = require('mongoose'),
    user = mongoose.model('users');

exports.get_user = function(req, res) {
    console.log(req.body.id);
    user.findById(req.body.id, function(err, user) {
        console.log(req.body);
        if(err)
            res.send(err);
            res.json(user);
        });
    };

userRoutes.js:

module.exports = function(app) {
    var users = require('../controllers/userController');
    app.route('/users/:userid')
       .get(users.get_user);
}

Upvotes: 0

Views: 812

Answers (1)

Andrew Li
Andrew Li

Reputation: 57924

I think you're confusing request parameters and request bodies. A request body is when you send information with the request like a payload, such as in a POST request when you send JSON to the server to, for example, create a new user:

{
  "username": "jd123",
  "email": "[email protected]",
  "name": "John Doe"
}

But in your case, you're looking for parameters, things passed through the URL like you've set up:

/users/:userid

That allows you to navigate to with a GET request:

/users/0

And then you can get the 0 as a string from req.params.userid not req.body.id. Request parameters and bodies are different. Parameters are for navigating to a varying route such as a user profile page, where the URL varies and reflects which route you want to go to by a user's ID.

Bodies are used for the payload of a request such as POSTing, PATCHing, and PUTing, giving information on what to update or create on the server.

Upvotes: 2

Related Questions