trurohit
trurohit

Reputation: 451

Req.body is empty when I POST using axios but when I use 'request' it's working fine

A little background - I have my NodeJS server running on port 3001 and my React application on port 3000. I've set up a proxy in my React application package.json to proxy all requests to port 3001 -

"proxy": "http://localhost:3001"

Now when I'm using Axios in my React application to make POST request on 'users/authentication' route on my NodeJS server, the request body is being parsed as blank on the Node server

const request = {
            method: 'POST',
            url: `/users/authenticate`,
            headers: {
                'Content-Type': 'application/json'
            },
            body: {
                email: email,
                password: password
            }
        };
        console.log(request);
        axios(request).then((res) => {
            //handle success 
        });
        }).catch((err) => //handleError ))

But unfortunately, the NodeJS application crashes because it's parsing req.body as blank. The relevant code on Server side -

//in index.js file
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

app.use('/users', users);

//in users.js file
const express = require('express');
const router = express.Router();
const userController = require('../controllers/users');
router.post('/authenticate', userController.authenticate);
module.exports = router;

//in UserController
const userModel = require('../models/user');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

module.exports = {
    authenticate: function (req, res, next) {
        console.log(req);
        userModel.findOne({ email: req.body.email }, function (err, userInfo) {
            if (err) {
                next(err);
            } else {
                if (bcrypt.compareSync(req.body.password, userInfo.password)) {
                    const token = jwt.sign({ id: userInfo._id }, req.app.get('secretKey'), { expiresIn: '1h' });
                    res.json({ status: "success", message: "user found!!!", data: { user: userInfo, token: token } });
                } else {
                    res.json({ status: "error", message: "Invalid email/password!!!", data: null });
                }
            }
        });
    },
}

But when I'm logging the request in the 'authenticate' function, the req.body is being parsed as blank which is making the application crash.

Now when I do this exact thing using 'Request' package on React, it's working completely fine. Below code using 'Request' library -

var options = {
            method: 'POST',
            url: 'http://localhost:3000/users/authenticate',
            headers:
            {
                'Content-Type': 'application/json'
            },
            form:
            {
                email: email,
                password: password
            }
        };
        console.log(options);

        request(options, function (error, response, body) {
            if (error) throw new Error(error);

            console.log(body);
        });

Any idea why it's working fine using Request and not on Axios?

The only problem with 'Request' is that I have to mention the complete URL - 'localhost:3000...' instead of just the route like in Axios.

Any other suggestions on how I could implement this better would be great also.

Upvotes: 0

Views: 2456

Answers (1)

Quentin
Quentin

Reputation: 943108

The property for adding data to the request body in Axios is called data not body.

Upvotes: 5

Related Questions