Valip
Valip

Reputation: 4650

How to use a google script web app with Node.js

I deployed a web app using google apps script and when I try to make requests to it using Node.js I get the following error:

Google Drive Page Not Found - Sorry, unable to open the file at this time

But everything works fine when I'm sending the requests using Postman.

This is my node.js code:

  const options = {
    'method': 'post',
    'gzip': true,
    'accept': '*/*',
    'content-length': 0,
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    'url': 'https://script.google.com/macros/s/script-id/exec'
  }
  request(options, (error, response, body) => {
    if(response.statusCode == 200) {
      res.sendStatus(200);
    }
    else {
      res.sendStatus(500);
    }
  });

This is the content of the google apps script web app:

function doPost(e) {
  return ContentService.createTextOutput(JSON.stringify({success: true}));
}

There are a couple more questions related to this topic, but the solution they provide is to remove /u/# from the URL ... which does not apply in my case.

Could this happen because I'm making requests from a http server to a web app deployed on https? That's the only thing that I'm thinking of...


Update:
I've also tried to send the request from a HTTPS node server and it still doesn't work.
Making a GET request works fine.

Upvotes: 0

Views: 5025

Answers (2)

Valip
Valip

Reputation: 4650

Making POST requests from a Node.js server to a web app deployed using Google Apps Script requires the 'Content-Length' header to be specified, and also the followAllRedirects option set to true, which is needed because the initial request is a redirect to another request that returns the response.

The working code looks like this:

  const options = {
    'method': 'post',
    'gzip': true,
    'body': [],
    'followAllRedirects': true,
    'headers': {
      'Content-Length': 0 // length of the specified `body`
    },
    'url': 'https://script.google.com/macros/s/scriptID/exec'
  }

  request(options, (error, response, body) => {
    if(response.statusCode == 200) {
      res.sendStatus(200);
    }
    else {
      res.sendStatus(500);
    }
  });

Hopefully this will help others that are facing this issue.

Upvotes: 2

Amit Agarwal
Amit Agarwal

Reputation: 11278

When publishing the web app inside Google Apps Script, make sure you have set the "Who has access" option to "Anyone, including anonymous".

Also, it may not work if your organization does not allow sharing of Drive files outside the organization. This setting can only be changed by the GSuite admin.

Upvotes: 0

Related Questions