【问题标题】:POST request from React to Express从 React 到 Express 的 POST 请求
【发布时间】: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


【解决方案1】:

您可以使用 body-parser 库:

安装使用: 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()。所以你也可以在不安装 body-parser 的情况下使用express.json()

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

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 2016-07-05
    • 2021-12-25
    • 2019-11-04
    • 2017-12-08
    • 2014-04-30
    • 2021-11-29
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多