I’m stuck trying to send info from my React app to Express and then make a new Airtable entry. Here’s what I’m doing:
In React:
sendData() {
const myData = {
name: 'test',
}
fetch('api/create', {
method: 'POST',
body: JSON.stringify(myData),
headers: {'Content-Type': 'application/json'}
})
}
In Express:
app.post('/api/create', jsonParser, async (req, res) => {
const newEntry = JSON.stringify(req.body);
console.log(newEntry);
table.create(newEntry, (err, record) => {
if (err) {
console.log(err);
res.json(err)
} else {
console.log(record);
res.json('Done!')
}
});
})
The Airtable API keeps giving me errors. But if I use table.create({'name':'test'}) instead of table.create(newEntry), it works fine. Am I messing up the JSON somehow? Help!
I’ve run into this exact issue before when working with Airtable and Express. The problem is that you’re double-stringifying the data. Airtable’s API expects a plain JavaScript object, not a JSON string.
Here’s what I’d suggest changing in your Express route:
app.post('/api/create', jsonParser, async (req, res) => {
table.create(req.body, (err, record) => {
if (err) {
console.log(err);
res.status(500).json(err);
} else {
console.log(record);
res.json(record);
}
});
})
This should solve your problem. The jsonParser middleware already parses the incoming JSON, so req.body is a JavaScript object. No need to stringify it again.
Additionally, returning the created record on success and setting the appropriate status code for errors can assist further debugging on the client side. Hope this helps!
I encountered a similar issue when integrating Airtable with Express. The problem lies in how you’re handling the JSON data. Airtable expects a JavaScript object, not a stringified JSON.
Try modifying your Express route like this:
app.post('/api/create', jsonParser, async (req, res) => {
table.create(req.body, (err, record) => {
if (err) {
console.error(err);
res.status(500).json({ error: 'Failed to create entry' });
} else {
res.json({ success: true, record: record });
}
});
})
This should resolve your issue. The jsonParser middleware already parses the incoming JSON, so req.body is ready to use. No need for additional stringification. Also, returning more detailed responses can help with debugging on the client side.
yo, i think i kno whats up. ur double-stringifying the data, man. airtable wants a plain js object, not a json string. try this in ur express route:
app.post(‘/api/create’, jsonParser, async (req, res) => {
table.create(req.body, (err, record) => {
if (err) {
console.log(err);
res.status(500).json(err);
} else {
res.json(record);
}
});
})
should fix it. jsonParser already parses the json, so req.body is good to go.