blackpink1234
blackpink1234

Reputation: 9

Trouble getting Post/Get Requests Between Google Web Apps

I have two Google Web Apps, one with a POST request and one with a GET request but the GET request seems to only receive a Google error page HTML and I'm not sure how to move forward.

The end goal is for the Main Web App to send data to the Second Web App, which will then generate email drafts in the user's folder. This cannot happen from the Main Web App because (due to unrelated reasons) Main Web App must execute as the developer. I've set the CreateDrafts web app to execute as the user, so the drafts end up in their inbox, not mine.

Main Web App Google Apps Script code

function doGet(e) {
  return HtmlService.createTemplateFromFile("Index").evaluate()
    .setTitle("Main Web App");
}

function sendPostRequest() {
  const webAppUrl = "https://script.google.com/macros/s/(secondWebAppId)/exec"; 

  try {
    const data = { message: "Post request sent" };

    const options = {
      method: "POST",
      contentType: "application/json",
      payload: JSON.stringify(data),
      muteHttpExceptions: true
    };

    const response = UrlFetchApp.fetch(webAppUrl, options);
    const content = response.getContentText();

    return JSON.parse(content);
  } catch (error) {
    return { success: false, message: "Error sending POST request" + error.toString() };
  };
};

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Main Web App</title>
</head>

<body>
  <button onclick="sendPostRequest()">Send POST Request</button>
  <p id="status"></p>
</body>

<script>
  function sendPostRequest() {
    google.script.run
      .withSuccessHandler(response => {
        console.log(response);
        if (response.success) {
          document.getElementById("status").innerText = "POST request successful" + response.message;
        } else {
          document.getElementById("status").innerText = "Error:" + response.message;
        }
      })
      .sendPostRequest();
  }
</script>

</html>

Second Web App Code

function doGet(e) {
  return ContentService.createTextOutput(
    JSON.stringify({ success: true, message: "GET request received successfully." })
  ).setMimeType(ContentService.MimeType.JSON);
}

function doPost(e) {
  try {
    const rawData = e.postData ? e.postData.contents : "{}";
    return ContentService.createTextOutput(
      JSON.stringify({ success: true, message: "POST received", data: rawData })
    ).setMimeType(ContentService.MimeType.JSON);
  } catch (error) {
    return ContentService.createTextOutput(
      JSON.stringify({ success: false, message: "Error: " + error })
    ).setMimeType(ContentService.MimeType.JSON);
  }
}

Both apps have the same appsscript.json:

{
  "timeZone": "America/Los_Angeles",
  "dependencies": {
    "enabledAdvancedServices": [
      {
        "userSymbol": "Gmail",
        "version": "v1",
        "serviceId": "gmail"
      }
    ],
    "libraries": [
      {
        "userSymbol": "OAuth2",
        "version": "43",
        "libraryId": "1B7FSrk5Zi6L1rSxxTDgDEUsPzlukDsi4KGuTMorsTQHhGBzBkMun4iDF"
      }
    ]
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "webapp": {
    "executeAs": "USER_ACCESSING",
    "access": "DOMAIN"
  }
}

I've tried the minimum viable code above but it seems to trigger an internal Google error and is not returning JSON. The error message I'm getting is

"Error:Error sending POST requestSyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"

(The HTML is from a Google error page)

Upvotes: 0

Views: 77

Answers (1)

EL SRY
EL SRY

Reputation: 1031

WebApp configuration

I have tried your code as is, and done some replication on how you might come up with this situation, and found that the status you're getting is HTTP 401 which means Unauthorized. This typically occurs when the published webApp is restricted to others.

In order for this to work you must provide authorization to your sender (Main Web App) from your receiver webApp (second webApp). You may achieve this by giving access to your webApp (second webApp).

When deploying your receiver (second webApp), It is necessary to change the Who has access configuration for it to be accessible to other webApps, or you may use some OAuth.

Steps: (second webApp)

  1. Deploy

  2. New Deployment

  3. Configuration --> Who has access (Adjust to your project's preference)

Sample configuration reference:

image

When you've set the right authorization to your second webApp, you may get the following result from your Main Web App:

POST request successfulPOST received

References:

Upvotes: 1

Related Questions