JStack
JStack

Reputation: 23

Google sheets apps script not reading parameters of post request

I need to send the responses from a form on my website to a google sheet. I finished my form so I have not included that here. I used an apps script doPost method to catch the requests and add the responses to a sheet.

The code used to fetch from my client side.

const data = {
      name: "john doe",
      email: "[email protected]",
      phone: "1234567890",
      message: "When does Malhar start?",
}

const scriptUrl = 'MY_SCRIPT_URL'; // Replace with your Google Apps Script URL

    try {
      const response = await fetch(scriptUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: new URLSearchParams(data)
      });

      if (response.ok) {
        alert('Form submitted successfully');
      } else {
        alert('Form submission failed');
      }
    } catch (error) {
      console.error('Error:', error);
}

My apps script code is below:

function doPost(e) {
  Logger.log( JSON.stringify(e));
  var sheet = SpreadsheetApp.openById('14Sz38NHK-mYINcb7B0QaYe_-djTK_NLysKBhEAf8_ec').getActiveSheet();
  var rowData = [];

  rowData.push(new Date()); // Timestamp
  rowData.push(e.parameter.name);
  rowData.push(e.parameter.email);
  rowData.push(e.parameter.phone);
  rowData.push(e.parameter.message);

  sheet.appendRow(rowData);

  var headers = {
    "Content-Type": "application/json",
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type,Authorization"
  };

  return ContentService.createTextOutput("Success")
    .setMimeType(ContentService.MimeType.JSON)
    .setHeaders(headers);
}

When I use Postman to check what the API is returning it says: Unexpected error while getting the method or property openById on object SpreadsheetApp.

However, i'm sure that the ID i've used is correct

Upvotes: 0

Views: 84

Answers (1)

Wicket
Wicket

Reputation: 38346

Review the Google Apps Script deployment as a web app and the spreadsheet-sharing settings. The deployment should be set as run as you or if you will in any other way, the spreadsheet sharing settings should be set accordingly, i.e, anyone with the link as editor.

Also, remove the following headers

"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type,Authorization"

as several headers will be overrided by Google.

Upvotes: 0

Related Questions