首页 > 解决方案 > 对表达做出反应:req.body 未定义

问题描述

我正在尝试将新数据推送到后端,但是当我在我的 post 方法中控制台日志 req.body 时,它打印出 undefine

下面是推送到后端的代码

...
 constructor(props) {
    super(props);

    this.state = {
      data: []
    };
 }

addNewItem = () =>{

     console.log("addNewItem");
     
     this.state.data.push({
       "name":"Tester seven", 
       "techs":["React & Redux", "Express", "MySQL"],
       "description":"Lore, sed do eiusmod tempor incididunt ut labore et",
       "checkin" :"08:00",
       "checkout":"19:00",
       "type":"Known Blacklisted"
    });

    fetch('/express_backend_post', {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(this.state.data)
    }).then(res =>{
      res.json()
    }).then(result =>{
      console.log("result ", result);
    })

    this.state.data.shift();

  }

这是我的 server.js

const cors = require('cors')
const { json } = require('body-parser')
const express = require('express'); //Line 1
const app = express(); //Line 2
const port = process.env.PORT || 5000; //Line 3

// This displays message that the server running and listening to specified port
app.listen(port, () => console.log(`Listening on port ${port}`)); //Line 6

app.use(cors())
app.use(json({limit:'50mb'}))

// create a POST route
app.post('/express_backend_post', (req, res) =>{
  console.log("req ", req.body);
 
})

在我的节点服务器上,它正在打印未定义。真的需要帮助才能知道我哪里出错了

标签: node.jsreactjsexpress

解决方案


这很可能是CORS问题。尝试设置Access-Control-Allow-Origin = '*'


推荐阅读