Home > Software engineering >  Request to Google Apps Scripts Implementation works from Postman but not from javascript
Request to Google Apps Scripts Implementation works from Postman but not from javascript

Time:03-13

I have this script defined for a google sheet in Apps Script:

function doPost(e) {
  var app = SpreadsheetApp.getActive();
  var sheet = app.getSheetByName('Web');

  var content = JSON.parse(e.postData.contents)
  sheet.getRange("A1").setValue(content);

  return ContentService.createTextOutput("Saved");
}

I Implemented it as Web Application and set the access to Anyone.

Then tried sending post request through postman to the generated url and it worked flawlesly. Also tried other postman like apps. Everything without issues. The content body of the request is always stored in the "A1" cell. enter image description here enter image description here

But when I want to send exactly the same request using Fetch API from my Vue.js web app. It fails with error: TypeError: Failed to fetch. Nothing else can be read from the error. No status code, nothing. Body of the function that is called on button click from my web app:

function sendForm() {

    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

    var raw = JSON.stringify({
        "test": "testing from vue"
    });

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        body: raw,
        redirect: 'follow'
    };

    fetch("https://script.google.com/macros/s/<id of the implementation>/exec", requestOptions)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));
}

The javascript code was generated from the postman itself, so there should be no differences.

This is the console output: enter image description here

Also tried axios. Similar issue, but the error was different: Network Error. enter image description here

I have no idea what to do or where to look. I googled for several hours but nothing I found helped. If anyone have an idea what could be the reason, I would be super grateful.

CodePudding user response:

From Then tried sending post request through postman to the generated url and it worked flawlesly., I confirmed that your Web Apps can be correctly used. In this case, in the case of your script, how about the following modification?

Modified script:

function sendForm() {
  var raw = JSON.stringify({"test": "testing from vue"});
  var requestOptions = {
    method: 'POST',
    body: raw,
  };
  fetch("https://script.google.com/macros/s/<id of the implementation>/exec", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));
}
  • When I tested this modified script using your Web Apps script, I confirmed that {test=testing from vue} is put to the cell.
  • Related