I have a form in my React app with several fields, and I want to send the form data to Google Sheets. I tried sending the data in JSON format (JSON.stringify(contactForm)), but I encountered a CORS error.
I found information suggesting that sending data as a string (key1=value1&key2=value2) can help avoid the CORS error. I’m using a Google Apps Script to handle the data, but nothing gets added to the sheet.
Here is my code in Apps Script:
const sheetName = 'Sheet2';
const scriptProp = PropertiesService.getScriptProperties();
function initialSetup() {
const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
scriptProp.setProperty('key', activeSpreadsheet.getId());
}
function doPost(e) {
const spreadsheetId = scriptProp.getProperty('key');
const sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName(sheetName);
if (!sheet) {
return ContentService.createTextOutput('Sheet not found');
}
const data = e.postData.contents;
const formData = parseFormData(data);
sheet.appendRow([formData.firstName, formData.lastName, formData.email, formData.phone, formData.zip]);
return ContentService.createTextOutput('Data added successfully');
}
function parseFormData(formData) {
const data = {};
if (typeof formData === 'string') {
formData.split('&').forEach(function (keyValue) {
const pair = keyValue.split('=');
data[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]).replace(/+/g, ' ');
});
}
return data;
}
And this is code in React app
const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
const contactFormText = `firstName=${contactForm.firstName}&lastName=${contactForm.lastName}&email=${contactForm.email}&phone=${contactForm.phone}&zip=${contactForm.zip}`;
try {
const response = await fetch(event.currentTarget.action, {
method: event.currentTarget.method,
headers: {
'Content-Type': 'text/plain',
},
body: contactFormText,
});
if (response.ok) {
handleOpenModal();
console.log(contactFormText, response);
setContactForm(INITIAL_CONTACTFORM_DATA);
} else {
console.error('Form submission failed');
}
} catch (error) {
console.error('Error:', error);
}
};
and form
<form
onSubmit={handleSubmit}
method="POST"
action="https://script.google.com/macros/s/xxxxxxxx/exec"
>