首页 > 解决方案 > 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());

标签: node.jsreactjsexpresspostpostman

解决方案


你为什么不尝试使用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' })


推荐阅读