Trouble sending data from React to Express and creating Airtable entries

I’m stuck trying to send an object from my React app to Express and then use it to make a new Airtable record. Here’s what I’ve got:

In React:

sendData() {
  const myData = {
    name: 'example'
  }
  fetch('api/save', {
    method: 'POST',
    body: JSON.stringify(myData),
    headers: {
      'Content-Type': 'application/json'
    }
  })
}

In Express:

app.post('/api/save', jsonParser, async (req, res) => {
  const newEntry = JSON.stringify(req.body);
  console.log(newEntry);
  myTable.create(newEntry, (err, record) => {
    if (err) {
      console.log(err);
      res.json(err);
    } else {
      console.log(record);
      res.json('All good!');
    }
  });
})

The Airtable API keeps giving me errors. But if I use myTable.create({'name':'example'}) instead of myTable.create(newEntry), it works fine. What am I doing wrong with the JSON handling? The Airtable docs make it seem like this should work. Any ideas?

I’ve dealt with this exact problem before, and it can be frustrating. The issue is definitely in your Express code. You’re stringifying the data again when it’s already been parsed by the jsonParser middleware.

Here’s what worked for me:

Remove the JSON.stringify(req.body) line completely. Just pass req.body directly to myTable.create(). Airtable’s API expects a JavaScript object, not a JSON string.

Also, I’d recommend using async/await for cleaner code. Something like this:

app.post(‘/api/save’, jsonParser, async (req, res) => {
try {
const record = await myTable.create(req.body);
res.json({ success: true, record });
} catch (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
}
});

This should solve your problem. Let me know if you run into any other issues!

hey mate, looks like ur stringify-ing the data twice. in express, req.body is already parsed as JSON. try removing JSON.stringify(req.body) and just use req.body directly in myTable.create(). that should fix it up for ya. lemme know if u need more help!

I encountered a similar issue when working with Airtable and Express. The problem lies in how you’re handling the data. Airtable expects an object, not a JSON string. Here’s what you should do:

Remove the JSON.stringify() call in your Express route. Simply pass req.body directly to myTable.create(). Like this:

app.post(‘/api/save’, jsonParser, async (req, res) => {
myTable.create(req.body, (err, record) => {
if (err) {
console.error(err);
res.status(500).json({ error: ‘Failed to create record’ });
} else {
res.json({ message: ‘Record created successfully’, record });
}
});
});

This should resolve your issue. Also, consider adding proper error handling and status codes for a more robust API.