【问题标题】:Req.body is empty when I POST using axios but when I use 'request' it's working fine当我使用 axios 发布时,Req.body 为空,但是当我使用“请求”时,它工作正常
【发布时间】:2019-08-25 10:10:38
【问题描述】:

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

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

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

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

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

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

但是当我在“身份验证”函数中记录请求时,req.body 被解析为空白,这导致应用程序崩溃。

现在,当我在 React 上使用“请求”包执行此操作时,它工作得非常好。下面的代码使用“请求”库 -

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

知道为什么它在使用 Request 而不是在 Axios 上运行良好吗?

“请求”的唯一问题是我必须提及完整的 URL - 'localhost:3000...' 而不是像 Axios 中那样只提及路由。

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

【问题讨论】:

    标签: javascript node.js reactjs express axios


    【解决方案1】:

    Axios 中向请求体添加数据的属性称为data 而不是body

    【讨论】:

    • 太棒了!不敢相信这是我错过的。非常感谢@Quentin
    猜你喜欢
    • 2020-10-19
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 2021-06-19
    • 2021-02-07
    • 2020-10-09
    • 1970-01-01
    相关资源
    最近更新 更多