最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

web applications - Why am I getting random success and failure responses when sending a POST request to Google Apps Script? - St

programmeradmin2浏览0评论

Issue:

  • Sometimes the request succeeds and I get the expected response from the server.
  • Other times, the request fails, and I don't get the expected response.

What I've Tried:

I’ve verified that my Google Apps Script doPost() method is correctly handling the POST request and responding with a valid JSON object.

Not able to fix this because of of the above issue

I Need some solution where i can fix this cors error and put successfully call of post api via google app script

Can you share some suggestion over it. I’m making an asynchronous POST request from my client-side JavaScript to a Google Apps Script endpoint, but I’m getting inconsistent results. Sometimes the request succeeds, and I get the expected response from the server. However, at other times, the request fails, and I don’t get the expected response.

Here’s an overview of the client-side code where I make the API request, followed by the server-side Google Apps Script (doPost method) code.

Client-Side JavaScript (API Handler):

async function API_HANDLER(request) {
  try {
    const url = "my script id"; // Replace with your actual URL

    IsLoading(true); // Start loading

    const fetchOptions = {
      redirect: "follow",
      method: "POST",
      headers: {
        "Content-Type": "text/plain;charset=utf-8", // Sending as text
      },
      body: JSON.stringify(request),
    };

    const response = await fetch(url, fetchOptions);

    if (response === undefined) {
      SHOW_ERROR_POPUP(error.message);
    }
    const data = await response.json();
    IsLoading(false); // Stop loading

    if (data?.status) {
      return data; // Resolve the data to be used by the caller
    } else {
      console.log("Error - ", data);
      SHOW_ERROR_POPUP(
        "Something went wrong, please contact any NKD Servants."
      );
    }
  } catch (error) {
    IsLoading(false); // Stop loading on error
    console.log(error);
    SHOW_ERROR_POPUP(error.message);
  } finally {
    IsLoading(false); // Stop loading regardless of success or error
  }
}

Server-Side Google Apps Script (doPost):

function doPost(e) {
  // Handle CORS preflight request (OPTIONS)
  if (e.postData.type === 'OPTIONS') {
    return ContentService.createTextOutput()
      .setMimeType(ContentService.MimeType.TEXT);
  }

  var data = JSON.parse(e.postData.contents);

  // Process and return response
  var response = {
    status: "success", // or other status depending on your logic
    message: "Request processed successfully"
  };

  return ContentService.createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON);
}

Issue:

  • Sometimes the request succeeds and I get the expected response from the server.
  • Other times, the request fails, and I don't get the expected response.

What I've Tried:

I’ve verified that my Google Apps Script doPost() method is correctly handling the POST request and responding with a valid JSON object.

Not able to fix this because of of the above issue

I Need some solution where i can fix this cors error and put successfully call of post api via google app script

Can you share some suggestion over it. I’m making an asynchronous POST request from my client-side JavaScript to a Google Apps Script endpoint, but I’m getting inconsistent results. Sometimes the request succeeds, and I get the expected response from the server. However, at other times, the request fails, and I don’t get the expected response.

Here’s an overview of the client-side code where I make the API request, followed by the server-side Google Apps Script (doPost method) code.

Client-Side JavaScript (API Handler):

async function API_HANDLER(request) {
  try {
    const url = "my script id"; // Replace with your actual URL

    IsLoading(true); // Start loading

    const fetchOptions = {
      redirect: "follow",
      method: "POST",
      headers: {
        "Content-Type": "text/plain;charset=utf-8", // Sending as text
      },
      body: JSON.stringify(request),
    };

    const response = await fetch(url, fetchOptions);

    if (response === undefined) {
      SHOW_ERROR_POPUP(error.message);
    }
    const data = await response.json();
    IsLoading(false); // Stop loading

    if (data?.status) {
      return data; // Resolve the data to be used by the caller
    } else {
      console.log("Error - ", data);
      SHOW_ERROR_POPUP(
        "Something went wrong, please contact any NKD Servants."
      );
    }
  } catch (error) {
    IsLoading(false); // Stop loading on error
    console.log(error);
    SHOW_ERROR_POPUP(error.message);
  } finally {
    IsLoading(false); // Stop loading regardless of success or error
  }
}

Server-Side Google Apps Script (doPost):

function doPost(e) {
  // Handle CORS preflight request (OPTIONS)
  if (e.postData.type === 'OPTIONS') {
    return ContentService.createTextOutput()
      .setMimeType(ContentService.MimeType.TEXT);
  }

  var data = JSON.parse(e.postData.contents);

  // Process and return response
  var response = {
    status: "success", // or other status depending on your logic
    message: "Request processed successfully"
  };

  return ContentService.createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON);
}
Share Improve this question edited Jan 20 at 17:44 Wicket 38.1k9 gold badges77 silver badges189 bronze badges asked Jan 20 at 12:45 honey mittalhoney mittal 294 bronze badges 11
  • 3 OPTIONS method is not supported by apps script. – TheMaster Commented Jan 20 at 13:32
  • What else we can you used? Can you please help, and share your suggestion – honey mittal Commented Jan 20 at 13:46
  • 1 Have you tried adding .setHeader('Access-Control-Allow-Origin', '*') in your return ContentService.createTextOutput(JSON.stringify(response)) .setMimeType(ContentService.MimeType.JSON); the purpose if you allow what domain you want to access from. Also considering script handling if preflight request. – Lime Husky Commented Jan 20 at 15:31
  • 1 Could you add the failed, unexpected response you get? It'd prove helpful in trying to identify how it is failling, which in turn would give useful insight into why it is sometimes failing. – HernanATN Commented Jan 20 at 16:35
  • 1 @honeymittal Use simple requests without json. send it as plain text to avoid preflight. – TheMaster Commented Jan 20 at 22:26
 |  Show 6 more comments

2 Answers 2

Reset to default 1

Concerning the server-side code, more specifically:

  // Handle CORS preflight request (OPTIONS)
  if (e.postData.type === 'OPTIONS') {
    return ContentService.createTextOutput()
      .setMimeType(ContentService.MimeType.TEXT);
  }

According to https://developers.google.com/apps-script/guides/web, e.postData.type returns the MIME type of the post body. OPTIONS is not among the MIME types listed in https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types/Common_types. To learn more about MIME types, read https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types, among other sources.

HTTP request using Axios from Client-side to Google App Script

I tried your code and sending data seems to have an error using Axios as an Alternative Javascript Library it is also a promise-based HTTP Client for node.js and the browser. We can bypass CORS using Axios request methods. You can read more about Axios here.

Sending data from Client-side to Backend Appscript works perfectly fine using this method. I reconstruct your code based on what I've tried.

Server-Side Google Apps Script (doPost):

function doPost(e) {

  var response = {
    status: "success", // or other status depending on your logic
    message: "Request processed successfully!",
    data: JSON.parse(e.postData.contents), // to get the Data contents from Client-side
    params: e // To check all object pass from Client-side.
    
  };

  return ContentService.createTextOutput(JSON.stringify(response))
    .setMimeType(ContentService.MimeType.JSON);
}

Here is the configuration of your client-side to make Axios work you need to install the javascript library in your Project Axios.

Client-Side Javascript (API Handler):

async function API_HANDLER(request) {
  try {
    const url = "https://script.google.com/macros/s/******/exec"; // Replace with your actual URL

    const axios = require('axios');
    const response = await axios.post(url, request);
    console.log(response);

    if (response === undefined) {
      console.log('error response')
    }

    // Rest of the code here.

  } catch (err) {

  } finally {

  }

}

Sample Response from Back-end to Client-Side:

data: {
    status: 'success',
    message: 'Request processed successfully!',
    data: { data: 'hello world!' },
    params: {
      contextPath: '',
      parameters: {},
      queryString: '',
      contentLength: 23,
      postData: [Object],
      parameter: {}
    }
  }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论