Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Script/Sheet Returns Bad Request 400

I have a fairly simple script running on a Google Sheet.

The script accepts a webhook POST and writes the content of the webhook as a new row in the spreadsheet.

The script does function as expected and it writes a new row when it receives data.

However, the app from where I'm sending the webhook receives back "Bad Request 400" error for some reason. Even though the script worked and it did what it was supposed to do.

This is a fiddle of the script I'm using.

If I call this manually, I do get a 200 response:

var response = UrlFetchApp.fetch("https://script.google.com/macros/s/AKfycbx5ubu78yi5sj2D9z-2m3Wqog604wY1ENwP3pZstnB95Mc5_N3b/exec", options);

This is a landing page with a form on it. When you submit the form, the form data gets pushed through a webhook to a Google Sheet. (Click on "Click Me To Test This Script" to see the form and if submit it, you'll see the actual sheet.)

like image 947
Hristian Kambourov Avatar asked Oct 18 '22 11:10

Hristian Kambourov


2 Answers

You can solve this by using the fetch(url, params) method of the UrlFetchApp class with the muteHttpExceptions option set to true. Below is an example of this for a post request.

var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(ObjectToSend),
    'muteHttpExceptions':true,
};

var noMancoResponse = UrlFetchApp.fetch('URL', options);
console.log("Status Code: " + String(noMancoResponse.getResponseCode()));

Hope this helps!

like image 80
Ramsinitus Avatar answered Dec 29 '22 01:12

Ramsinitus


I had the same problem and after a lot of resending of the HTTP request, i realized it was because of Content Security Policy header. If it is set by the server and your origin doesn't satisfy its rules, then the browser will show error 400.

It would be great if there was an option in UrlFetchApp to suppress this error.

I haven't found any solution to fix it. please let me know if you do so.

like image 24
Moradnejad Avatar answered Dec 29 '22 01:12

Moradnejad