Home > Software design >  POST Request Body is empty
POST Request Body is empty

Time:12-16

Task

  • Parse a CSV file
  • Send the data to an API enpoint
  • Save data to MySql database

Problem

The request body is showing up empty when I send data via fetch. However, I can send and see the body data if I use Postman.

I've added a console.log(req.body) and it's printing out {} to the console.

Parse and Send Data to Endpoint

  const changeHandler = (event) => {
    Papa.parse(event.target.files[0], {
      header: true,
      skipEmptyLines: true,
      complete: function (results) {
        results.data.forEach(entry => {
          // Create the data object.
          let data = {};
          let keys = ['Date', 'Description', 'Debit Amount'];
          for (let key in entry) {
            if (keys.includes(key)) {
              data[key.toLowerCase().replaceAll(' ', '_')] = entry[key];
            }
          }
          // Send data to server
          fetch('http://localhost:3001/api/create_transactions', {
            method: 'POST',
            mode: 'no-cors',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data),
          }).then(function (response) {
            console.log(response);
          })
        });
      },
    });

    // Reset file input
    event.target.value = null;
  };

Save Data to MySql

app.use(express.json());

const crypto = require('crypto');

app.post("/api/create_transactions", (req, res) => {
  console.log(req.body);
  /*
  let hash = crypto.createHash('md5').update(req.body['date']   req.body['description']   req.body['debit_amount']).digest('hex');

  let data = [
    hash,
    req.body['date'],
    req.body['description'],
    req.body['debit_amount'],
  ];

  db.query('insert into transactions (`hash`, `date`, `description`, `debit_amount`) values (?, ?, ?, ?)', data, (err, result, fields) => {
    if (err) {
      console.log(err);
    } else {
      console.log(result);
      res.send(JSON.stringify({"status": 200, "error": null, "response": result}))
    }
  });
  */
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

CodePudding user response:

According to this post Fetch: post json data, application/json change to text/plain you can not change the Content-Type to application/json if you are using no-cors. So I will have to enable cors if I want to use fetch.

Using this tutorial https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/ I was able to enable cors on my nodejs server and receive the proper headers.

CodePudding user response:

Try to use express's bodyParser app.use(express.bodyParser());

  • Related