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

标签 javascript node.js reactjs express axios

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

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

现在,当我在 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 ))

但不幸的是,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 上使用“Request”包执行此操作时,它工作得很好。下面的代码使用“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);
        });

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

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

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

最佳答案

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

关于javascript - 当我使用 axios POST 时,Req.body 为空,但当我使用 'request' 时,它工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57645114/

相关文章:

javascript - 在react js中预览并上传同一组件中的两个单独的图像

javascript - 以编程方式重命名功能

javascript - 将 <img> 替换为 <object>

html - 如何在本地通过 Node.js 提供静态文件?

node.js - ionic 平台添加android : Error: Cannot find module ‘./source-map/source-map-generator’

javascript - Relay 中的嵌套片段数据始终相同

javascript - React-Sound 状态管理问题

javascript - Vue.js - 如何将 "multi-level-nested"成员 react 性地添加到对象

javascript - 在 javascript 中获取 C# 值

javascript - NodeJS 中每个元素中的表连接