I’ve encountered an issue with my Airtable script that attempts to send POST requests to my Node.js API. The problem is that instead of a POST, my API receives an OPTIONS request, leading to a 405 Method Not Allowed error.
Working example: I’ve confirmed that the API endpoint operates correctly when tested using Postman.
What’s not working: When executing the script from Airtable, I get an error related to Cross-Origin Resource Sharing (CORS).
Error message from Airtable:
TypeError: Failed to fetch
at main on line 27
This issue could be due to CORS settings.
Console error on server side:
OPTIONS /api/webhook 405 Method Not Allowed
Here is my updated Airtable script:
let myTable = base.getTable('Onboarding');
let myView = myTable.getView('Grid view');
let allRecords = await myView.selectRecordsAsync();
let currentRecord = allRecords.records[0];
var payload = {user:
{
"firstName": currentRecord.getCellValueAsString('firstName'),
"lastName": currentRecord.getCellValueAsString('lastName'),
"email": currentRecord.getCellValueAsString('email'),
},
};
let apiResponse = await fetch('https://example-api.com/api/webhook', {
method: 'POST',
body: JSON.stringify(payload),
headers: {
"Content-Type": 'application/json',
"Accept": "application/json",
}
});
let jsonResponse = await apiResponse.json();
await myTable.updateRecordAsync(currentRecord.id, {
apiResponse: jsonResponse,
});
My Node.js API’s handler function:
export default async function handler(request, response) {
const { method } = request;
console.log("Request method:", method);
switch (method) {
case "POST":
console.log("Request body:", request.body);
return processRequest(request, response);
case "OPTIONS":
response.setHeader("Allow", "POST");
response.setHeader("Allow", ["GET", "POST", "PUT", "DELETE", "OPTIONS"]);
response.status(405).end(`Method ${method} Not Allowed`);
break;
}
}
const processRequest = async (request, response) => {
console.log("REQUEST BODY: ", request.body);
response.status(200).json("Success");
};
What can I do to resolve this CORS problem and ensure my API gets POST requests instead of OPTIONS?