【问题标题】:react to express : req.body is undefined对表达做出反应:req.body 未定义
【发布时间】:2021-12-06 04:44:52
【问题描述】:

我正在尝试将新数据推送到后端,但是当我在我的 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);
 
})

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

【问题讨论】:

  • 您是否在 express 中包含了正文解析器?
  • 我已经编辑了我的问题以包含正文解析器,但现在我有另一个错误413 payload too largeUncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

标签: node.js reactjs express


【解决方案1】:

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

【讨论】:

  • 我已更新我的问题以包括 CORS,但这不是问题
【解决方案2】:

问题不仅在于缺少 CORS,还在于缺少 body-praser。从 express@4.17.1 开始,body-praser 已经与 express 捆绑在一起,点击here了解更多信息。

下面是我完整的工作 server.js

var fs = require('fs');
const cors = require('cors')

// function to encode file data to base64 encoded string
function base64_encode(file) {
  // read binary data
  var bitmap = fs.readFileSync(file);
  // convert binary data to base64 encoded string
  return new Buffer.from(bitmap).toString('base64');
}

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


var data = [
  {
      name: "Tester one",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lorem ipsum doabore et",
      checkin: "09:00",
      checkout:"18:30",
      type:"Known Staff",
      image: base64_encode('./src/img/male.png')
  },
  {
      name: "Tester two",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lorem ipsum dolor sit amet, consectetet",
      checkin: "09:00",
      checkout:"18:30",
      type:"Known Blacklisted",
      image: base64_encode('./src/img/female.png')
  },
  {
      name: "Tester three",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lorem ipsumabore et",
      checkin: "09:00",
      checkout:"18:30",
      type:"Unknown Visitor",
      image: base64_encode('./src/img/blacklist.png')
  },
  {
      name: "Tester four",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lorem ipsum dolor labore et",
      checkin: "09:00",
      checkout:"18:30",
      type:"Known Staff",
      image: base64_encode('./src/img/unknown_person.png')
  },
  {
      name: "Tester five",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lorem ipncididunt ut labore et",
      checkin: "09:00",
      checkout:"18:30",
      type:"Known Staff",
      image: base64_encode('./src/img/blacklist.png')
  },
  {
      name: "Tester six",
      techs: ["React & Redux", "Express", "MySQL"],
      description: "Lore, sed do eiusmod tempor incididunt ut labore et",
      checkin: "09:00",
      checkout:"18:30",
      type:"Known Staff",
      image: base64_encode('./src/img/unknown_person.png')
  }
]

const corsOptions = {
  origin: true,
  methods: ['GET, POST'],
  credentials: true
};

app.use(cors(corsOptions))

app.use(express.urlencoded({limit: '50mb', extended: true}));
app.use(express.json({limit: '50mb'})); // app.use(bodyParser.json())


// create a GET route
app.get('/express_backend', (req, res) => { //Line 9
  res.send(data);

  
});

// create a POST route
app.post('/express_backend_post', (req, res) =>{
  req.body[5].image=  req.body[5].image.replace("data:image/png;base64,", "")
  data = req.body;
})

如果有更好的方法来优化或缩短它以达到相同的结果,请随时在下面发表评论,我仍在学习并欢迎任何评论以改进和成长为程序员

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-18
    • 2022-11-01
    • 2012-02-28
    • 2016-09-05
    • 1970-01-01
    相关资源
    最近更新 更多