node.js - Express:从 React 前端发送 POST 请求以空正文发送,但从 Postman 发送正确发送正文
问题描述
我正在制作一个带有 React 前端和 Node Express 后端的 Web 应用程序。当我向我的一个端点发送一个带有 JSON 正文的 POST 请求,并从服务器打印 req.body 的内容时,我得到一个空对象。但是,当我从 Postman 发送完全相同的请求时,它可以完美运行。
在开发人员工具的“网络”选项卡中,我看到此错误消息。请求的有效负载似乎是正确的。
这是我的前端请求代码:
fetch('http://localhost:3000/building', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({buildingAttempt: 'test'}),
}).then(function (res) {
// deal with result
}).catch(function (error) {
console.log(error);
}).finally(function () {
});
在后端,我打印 req.body 的内容进行测试:
app.use('/building', (req, res) => {
console.log(req.body);
// other code
}
我已经尝试包含下面的代码片段来处理起源问题:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
我还添加了 json 正文解析器:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
解决方案
你为什么不尝试使用axios?它对你来说更容易。
创建一个 services 文件夹,并在其中创建一个 api.js 文件
import axios from 'axios'
export const api = axios.create({
baseUrl: 'http://localhost:3000'
})
//file where you're making the request
import api from '...path...'
api.post('/building', { test: 'test data' })
推荐阅读
- c# - 如何从 Http 响应中提取 GET 值?
- python - 将一个列表变成一个列表,其中每个项目具有多重性 1
- python - 这个python中的代码片段没有执行。请指出错误吗?我是初学者
- python - 为什么我的绘图课画的是秒,而不是 cosec 或 cot?
- python - 当我单击 shell 时运行程序时,tkinter 窗口不会打开
- python - Django CreateView 表单未提交
- python-3.x - 如何在 Python Google Cloud 函数中返回特定状态
- sql - Oracle DISTINCT 查询与结果集中不需要的字段上的 ORDER BY
- php - 如何在 PHP 中将 Hex 转换为 Dec int32,反之亦然?
- javascript - 在 vue.js 中检测滚动