sách gpt4 ai đã đi

Req.body trống khi tôi POST bằng axios, nhưng nó hoạt động tốt khi tôi sử dụng 'request'

In lại 作者:太空宇宙 更新时间:2023-11-04 03:00:36 32 4
mua khóa gpt4 Nike

一些背景知识 -我的 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())

ứng dụng.use('/người dùng', người dùng);

//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) {
tiếp theo(err);
} khác {
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 } });
} khác {
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 中那样仅提及路由。

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

1 Câu trả lời

Axios中向请求体添加数据的属性称为dữ liệuCòn hơn làthân hình.

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

32 4 0
太空宇宙
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com