0

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}`);
});
FatGuyLaughing
  • 205
  • 1
  • 4
  • 10
  • Does this answer your question? [Trying to use fetch and pass in mode: no-cors](https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors). And this? [How to enable cors nodejs with express?](https://stackoverflow.com/q/43150051/283366) – Phil Dec 15 '22 at 06:11
  • it's not seems to be CORs issue at all @Phill – M Maavia Dec 15 '22 at 06:19
  • can you console log the req.headers? – M Maavia Dec 15 '22 at 06:27
  • @MMaavia I was able to log the req.headers. I noticed something that shouldn't be. The `content-type` is still set to `text/plain`. I tried setting my fetch headers to `new Headers({'Content-Type': 'application/json'})` and I'm still getting 'text/plain' in the request headers. – FatGuyLaughing Dec 15 '22 at 19:06
  • According to this post https://stackoverflow.com/questions/39689386/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`. – FatGuyLaughing Dec 15 '22 at 19:21

2 Answers2

0

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.

FatGuyLaughing
  • 205
  • 1
  • 4
  • 10
-1

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