【问题标题】:Express: Sending POST request from React frontend sends in an empty body, but sending from Postman sends the body correctlyExpress:从 React 前端发送 POST 请求以空正文发送,但从 Postman 发送正确发送正文
【发布时间】:2020-11-10 06:12:51
【问题描述】:

我正在制作一个带有 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
}

我已经尝试在下面包含代码 sn-p 来处理源问题:

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

【问题讨论】:

  • Postman 不是浏览器,并且不执行浏览器执行的通用 preflight request,所以最好你忘记允许 http OPTIONS 动词,浏览器甚至永远无法访问发送 POST。打开您的开发工具,转到“网络”选项卡,看看当您尝试fetch 调用时会发生什么:发送了哪些网络请求,带有哪些标头,哪些有效负载,以及它们的服务器响应是什么? (当然:确保将这些细节放在你的帖子中,因为它们很重要)
  • 谢谢!在网络选项卡上,它表示请求的状态是“(失败)net::ERR_FAILED”。不过,有效载荷似乎是正确的。

标签: node.js reactjs express post postman


【解决方案1】:

尝试使用我认为的 cors

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 试试这个,告诉我会发生什么
    • body 对象还是空的。
    • 从建筑物中删除'/'并检查路径是否正确
    • 另外,你能展示一下代码,或者一些有助于可视化问题的东西吗??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 2019-05-16
    • 2021-06-18
    • 2015-12-22
    相关资源
    最近更新 更多