簡體   English   中英

當我使用axios進行發布時,req.body為空,但是當我使用“請求”時,它工作正常

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

背景知識-我的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解析為空白。 服務器端的相關代碼-

//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中的路由。

關於如何更好地實現這一點的任何其他建議也都很好。

在Axios中將數據添加到請求主體的屬性稱為data而非body

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM