Home > Blockchain >  react to express : req.body is undefined
react to express : req.body is undefined

Time:10-20

I am trying to push new data to the backend, but when I console log req.body at my post method, it is prints out undefine

Below is the code for pushing to backend

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

  }

This is my 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);
 
})

At my node server, it is printing undefined. Really need help to know where I went wrong

CodePudding user response:

it is most likely a CORS issue. Try setting Access-Control-Allow-Origin = '*'

CodePudding user response:

The issue was not only because of just missing CORS, but also the missing of body-praser. As of [email protected], body-praser has been bundle together with express, click here for more information.

Below is my full working 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;
})

If there is a better way to optimize it or shorten it achieve the same result, feel free to comment below, I am still learning and welcome any comment to to improve and grow as a programmer

  • Related