Search code examples
reactjsexpressairtable

Passing an object from React to Express and creating a new Airtable record


I’m having trouble passing an object from React to Express, and then creating an airtable record in Express.

In react, i am sending an http request to Express via:

finalSubmit() {
  const airtableObj = {
    title: 'hi',
  }
  fetch('api/submit',{
    method: 'POST',
    body: JSON.stringify(airtableObj),
    headers: {"Content-Type": "application/json"}
  })
}

My Express code is:

app.post('/api/submit', jsonParser, async (req, res) => { 
    const newStudy = JSON.stringify(req.body);   
    await console.log(newStudy); 
    table.create(newStudy, function(err, record) {  
        if (err) {console.log(err); res.json(err)} else {console.log(record), res.json('Success!')}
    });   
}) 

However, I keep getting errors back from the airtable api. IF I replace the 4th line of my express code with:

table.create({“title”:“hi”} 

instead of

table.create(newStudy)

, everything works fine. It seems like this should work according to the airtable documentationt... (https://airtable.com/api). Is there something I am doing wrong with how I am manipulating my data in and out of JSON? Thanks


Solution

  • This appears to be happening because you're calling JSON.stringify(req.body), which you don't need to do.

    table.create takes an object, not a string, so you'll want to do something like this:

    const newStudy = req.body;
    table.create(newStudy, function(err, record) {  
      // ...
    });