Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doPost not working in Google app script

I came across various questions but none of them could solve my problem. I wrote a simple doPost() code in google app script:

function doPost(e){
  Logger.log("Hello World");
}

Then I deployed it as a web app and pasted the url on hurl.it to make a post request. However, there is nothing being logged in the log and the response is 200 (Ok). I think it is not going inside this doPost() function. Can anyone guide as to what am I doing wrong here?

like image 702
Anurag Mishra Avatar asked Jul 18 '17 10:07

Anurag Mishra


2 Answers

Your implementation does not meet all the requirements needed for a web app. Here's an excerpt from the documentation (link):

Requirements for web apps

A script can be published as a web app if it meets these requirements:

  • It contains a doGet(e) or doPost(e) function.
  • The function returns an HTML service HtmlOutput object or a content service TextOutput object.

Here are some examples:

function doGet(e) {
  var params = JSON.stringify(e);
  return HtmlService.createHtmlOutput(params);
}

function doPost(e) {
  return ContentService.createTextOutput(JSON.stringify(e.parameter));
}

And just for completeness, you must also redeploy your web App as a new version every time you make changes to the code. Redeploying under an already existing version does not work, you have to make a new version for your changes to take hold.

Also using the standard Logger.log to trace changes within doGet(e) or doPost(e) is unreliable with web apps as they are executed asynchronously. I would recommend logging your output to a spreadsheet. There is an awesome script library called BetterLog that extends the Logger API to do just that; it can be found at the following link:

https://github.com/peterherrmann/BetterLog


UPDATE 2018-07-18

Apps Script now supports StackDriver Logging which is accessible from the Apps Scripts editor's View menu.

like image 116
TheAddonDepot Avatar answered Sep 19 '22 11:09

TheAddonDepot


in order for the "exec" version of the published Web App URL to run with any new changes, you must publish a new version every time that you make a change to your script. It does not matter how small the change is. Instead of using Logger.log("Hello World"); I would write a value to a spreadsheet.

SpreadsheetApp.openById(id).getSheetByName(name).appendRow(['test']);

There are 2 different URL's for your Web App. One with 'dev' on the end and the other with 'exec' on the end. The 'dev' version is always the current code. The 'exec' version never changes unless you publish a new version.

like image 28
Alan Wells Avatar answered Sep 18 '22 11:09

Alan Wells