繁体   English   中英

Express:从 React 前端发送 POST 请求以空正文发送,但从 Postman 发送正确发送正文

[英]Express: Sending POST request from React frontend sends in an empty body, but sending from Postman sends the body correctly

我正在制作一个带有 React 前端和 Node Express 后端的 web 应用程序。 当我向我的一个端点发送一个带有 JSON 主体的 POST 请求,并从服务器打印 req.body 的内容时,我得到一个空的 object。 但是,当我从 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? 它对你来说更容易。

创建一个服务文件夹,并在其中创建一个 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' })

尝试使用 cors 我认为

  1. npm 安装 cors
  2. 在服务器上导入 cors
  3. app.use(cors())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM