当我使用axios进行发布时,req.body为空,但是当我使用“请求”时,它工作正常

时间:2019-08-25 10:10:38

标签: javascript node.js reactjs express axios

一些背景- 我的NodeJS服务器运行在端口3001上,我的React应用程序运行在端口3000上。我已经在我的React应用程序package.json中设置了一个代理,以代理对端口3001的所有请求-

>>> checkList([2,3,4,9,9,5,1])
True

现在,当我在React应用程序中使用Axios在NodeJS服务器上的“用户/身份验证”路由上发出POST请求时,请求正文在Node服务器上被解析为空白

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

但是不幸的是,NodeJS应用程序崩溃,因为它将req.body解析为空白。服务器端的相关代码-

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 ))

但是,当我在“ authenticate”功能中记录请求时,req.body被解析为空白,这使应用程序崩溃。

现在,当我在React上使用'Request'包执行此操作时,它的工作就完全正常了。下面的代码使用“请求”库-

//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 });
                }
            }
        });
    },
}

有人知道为什么使用Request而不是在Axios上可以正常工作吗?

“请求”的唯一问题是,我不得不提到完整的URL-“本地主机:3000 ...”,而不仅仅是Axios中的路由。

关于如何更好地实现这一点的任何其他建议也都很好。

1 个答案:

答案 0 :(得分:4)

在Axios中将数据添加到请求正文的属性称为data而不是body

相关问题