Apps Script API returning 404 error for existing project. Error returned as HTML rather than JSON

假如想象 提交于 2021-02-20 00:41:30

问题


I was attempting to run an Apps Script function using the Apps Script API. I set up the script in the console, and created an oauth client ID for the script. I configured the authorisation screen and deployed the script as API executable. I tested the api function calling in the same script but got a 404 error saying:

The Requested URL /v1/scripts/{{my_script_id}}:run was not found on this server.

The response came back as HTML. I also noticed that the script seems to make it's own client ID when it's called from the API.

I tried disabling and re-enabling the API which didn't work. I think it may be a problem with the calling application not being in the same project but I'm not sure how to do that as the Google documentation is unclear.

function trigger(){
  var bogus = DriveApp.getRootFolder();
  var argument = ["Value0", "Value1", "Value2", "Value3", "Value4", "Value5"]; 

  //         https://www.googleapis.com/auth/script.external_request
  //         https://www.googleapis.com/auth/spreadsheets

 var postRequest = {
    "Content-Type": "application/json",
    "headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
    "function": "setStatus",
    "muteHttpExceptions": true,
    "parameters": [argument],
    "devMode": false
 };

  try{
    var response = UrlFetchApp.fetch("https://script.googleapis.com/v1/scripts/{{my_script_id}}:run", postRequest);
    Logger.log(response);
  }catch(err){
    Logger.log(err);
  }
}

I expected some form of error in the form of JSON or maybe even for the function to run, what I got was a HTML document which displayed a 404 error when displayed.


回答1:


You're not POSTing the request. Default .fetch method is GET.

Add this in postRequest object:

method: "POST",

payload is also missing from your postRequest.

Snippet:

var postRequest = {
    "method":"POST", //added
    "contentType": "application/json", //key changed
    "headers": { "Authorization" : "Bearer " + ScriptApp.getOAuthToken()},
    "muteHttpExceptions": true,
     "payload": JSON.stringify({   //added
      "function": "setStatus",
      "parameters": argument, //removed []
      "devMode": false
    })
 };

References:

  • UrlfetchApp
  • Script:run


来源:https://stackoverflow.com/questions/55708760/apps-script-api-returning-404-error-for-existing-project-error-returned-as-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!