当我使用 axios POST 时,Req.body 为空,但当我使用“request”时,它工作正常

tru*_*hit 0 javascript node.js express reactjs axios

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

"proxy": "http://localhost:3001"
Run Code Online (Sandbox Code Playgroud)

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

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 ))
Run Code Online (Sandbox Code Playgroud)

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

//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 });
                }
            }
        });
    },
}
Run Code Online (Sandbox Code Playgroud)

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

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

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);
        });
Run Code Online (Sandbox Code Playgroud)

知道为什么使用 Request 而不是在 Axios 上工作得很好吗?

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

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

Que*_*tin 5

Axios 中用于向请求正文添加数据的属性称为datanot body