【发布时间】:2022-01-25 08:59:17
【问题描述】:
所以我在从 React 向我的 Express 服务器后端发出发布请求时遇到问题:据我所知,请求有效负载的结构正确,并且我能够从服务器发回硬编码的响应并接收它在前端。
但是,问题是数据本身似乎没有到达服务器 - 当我在服务器上使用 console.log(req.body) 时,它是 undefined。 我完全被难住了。
我检查请求时的网络选项卡:
- 标头状态为 200,请求已完成
- Payload 显示格式正确的 json 对象
body: {url: "https://example.com"} - 响应也正确返回!
{response: "foo"}
客户端API函数:
const callBackendAPI = async (query) => {
const response = await axios.post('/', {
body: { url: query },
});
}
注意:我已将 "proxy": "http://localhost:3001" 添加到客户端的 package.json 中。
在服务器中:
const express = require('express');
const app = express();
app.post('/', (req, res) => {
console.log(req.body); // <------ **Here's the issue, there's nothing here**
res.json({ response: 'foo' });
// however, if I send res.json(req.body), the response is empty in Network tab
});
【问题讨论】:
-
你在使用正文解析器
-
FML。不。我不是。
-
就这样?
const bodyParser = require('body-parser');app.use(bodyParser.urlencoded({ extended: false })); -
是的,任何配置都应该工作
-
试试
App.use(express.json());
标签: node.js reactjs express server axios