表达:从React前端发送POST请求会发送一个空的正文,但从Postman发送会正确发送该正文

时间:2020-07-20 22:35:49

标签: node.js reactjs express post postman

我正在制作一个带有React前端和Node Express后端的Web应用程序。当我将带有JSON正文的POST请求发送到我的一个端点,并从服务器打印req.body的内容时,我得到了一个空对象。但是,当我从Postman发送完全相同的请求时,它的运行效果很好。

在开发人员工具的“网络”标签中,我看到了这个error message。请求的有效负载似乎是正确的。

这是我的前端请求代码:

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

尝试使用我认为的cors

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