简体   繁体   中英

POST Request Body is empty

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}`);
});

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM