skip to Main Content

I am trying to execute a simple apps script function deployed as web app. This web app has a single function doPost with a simple console print statement. When I try to execute this script from JS client using fetch method, I am getting error "Script function not found: doGet".
However when I execute this from a HTTP client tool like Bruno I am able to execute the web app and the results are as expected.
Please suggest how to resolve this issue.

Apps script code as below

function doPost(e) {

  console.log('Posted data from client is..',JSON.stringify(e))
}

Client side JS Code as below

const url = "https://script.google.com/macros/s/myscriptid/exec";

let appbody = {
                  "fruit_name" : "Orange",
                  "qty" : "210"
              }

let optionsin = {      
                  "headers" : {
                "Content-Type": "application/json"
                            },
                  "method": "POST",
                  "body": JSON.stringify(appbody)
              }

function samplefunc()

  {
       try 
        {
               console.log("About to call fetch")
                   fetch(url, {optionsin})
                .then(response => {return response.json()} )
                .then(result => {console.log(' result from  api call', result);
                         })  
                 } 
       catch (error) 
                 {
                    console.log('Error in triggering fetch', error.message)
                 }
  }
samplefunc();

2

Answers


  1. The issue you’re facing with doPost not being called when using fetch but working with an HTTP client likely boils down to how the request is being sent. Here’s a breakdown of the problem and potential solutions:

    The Problem:

    Google Apps Script expects POST requests to have a specific format to trigger the doPost function.
    fetch might not be adding the necessary headers or payload format that Apps Script recognizes as a POST request.
    HTTP client tools like Bruno might be pre-configuring these details, causing them to work as expected.
    Potential Solutions:

    Modify fetch request:

    Update the optionsin object in your client-side JS code to explicitly include the POST method and necessary headers:
    JavaScript

    let optionsin = {
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": JSON.stringify(appbody)
    }
    1. Use the GAppsScript library (if applicable):

    If you’re using a framework like clasp to deploy your Apps Script as a web app, consider using the GAppsScript library. This library simplifies calling Apps Script functions from your client-side code and handles the request formatting automatically. Refer to the library’s documentation for specific usage instructions.

    1. Check Apps Script Logs:

    Even if doPost isn’t being triggered, there might be clues in the Apps Script logs. Go to Tools > Script editor in your Google Apps Script project. In the Script editor, navigate to Run > View logs to see if any errors or warnings are being logged related to your function call.

    Login or Signup to reply.
  2. Modification points:

    • From your showing Javascript, I suppose that your Web Apps is deployed as Execute as: Me and Who has access to the app: Anyone. If your actual setting is different from this, the below script might not be able to be used. Please be careful about this.

    • In the case of your showing doPost, no value is returned. And, I’m worried that even when doPost is run with the event object e, the log might not be shown in the log. But, if your Google Apps Script project has already been linked with the Google Cloud Platform project, the log can be seen. Ref (Author: me)

    • In your Javascript, { optionsin } of fetch(url, { optionsin }) is the same with { optionsin: optionsin }. In this case, the values in optionsin is not used. I guessed that this might be the reason for your current issue of Script function not found: doGet.
      When these points are reflected in your script, how about the following modification?

    Modified script:

    Google Apps Script side:

    function doPost(e) {
      console.log('Posted data from client is..', JSON.stringify(e))
      return ContentService.createTextOutput(JSON.stringify(e));
    }
    

    Javascript side:

    Please set your Web Apps URL to url.

    const url = "https://script.google.com/macros/s/myscriptid/exec";
    
    let appbody = {
      "fruit_name": "Orange",
      "qty": "210"
    };
    let optionsin = {
      "method": "POST",
      "body": JSON.stringify(appbody)
    };
    
    function samplefunc() {
      try {
        console.log("About to call fetch");
        fetch(url, { ...optionsin })
          .then(response => { return response.json() })
          .then(result => {
            console.log(' result from  api call', result);
          });
      } catch (error) {
        console.log('Error in triggering fetch', error.message);
      }
    }
    
    samplefunc();
    

    Testing:

    When this Javascript is run, the following value is given as the event object e. Also, this value is also returned to Javascript by return ContentService.createTextOutput(JSON.stringify(e)). You can see it in the console.

    {
      "postData": { "contents": "{"fruit_name":"Orange","qty":"210"}", "length": 35, "name": "postData", "type": "text/plain" },
      "parameters": {},
      "parameter": {},
      "contentLength": 35,
      "contextPath": "",
      "queryString": ""
    }
    

    Note:

    References:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search