POST 从 React 到 Express 的请求

POST request from React to Express

所以我在从 React 向我的 Express 服务器后端发出 post 请求时遇到问题:据我所知,请求有效负载的结构正确,并且我能够发回来自服务器的硬编码响应并在前端接收它。

但是,问题是数据本身似乎没有到达服务器 - 当我 console.log(req.body) 在服务器上时,它是 undefined我完全被难住了。

检查请求时的网络选项卡:

Client-side 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
});

您可以使用正文解析器库:

安装使用: npm install body-parser

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json())

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
});

显然他们根据 https://github.com/expressjs/express/releases/tag/4.16.0 从 4.16.0 开始添加了 express.json() 。所以你也可以使用 express.json() 而无需安装 body-parser。

const express = require('express');
const app = express();
app.use(express.json())

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
});