2

我收到错误:

收到无效的 JSON 有效负载

尝试使用 Apps 脚本 API 创建新的 Apps 脚本文件时。

我该如何解决这个错误?

function createNewFile() {
  var d,options,payload,response,theAccessTkn,url;

  theAccessTkn = ScriptApp.getOAuthToken();

  //See https://developers.google.com/apps-script/api/reference/rest/v1/projects/create
  url = "https://script.googleapis.com/v1/projects";

  d = new Date().toString().slice(0,10);

  payload = {
    "title": "AA_" + d
  }

  options = {
    "method" : "POST",
    "muteHttpExceptions": true,
    "headers": {
       'Authorization': 'Bearer ' +  theAccessTkn
     },
    "payload": JSON.stringify(payload)
  };

  response = UrlFetchApp.fetch(url,options);

  Logger.log(response)

  return response;
}

我在清单文件中设置了授权范围,以避免需要添加 OAuth 库:

{
  "timeZone": "America/New_York",
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.projects",
    "https://www.googleapis.com/auth/script.external_request"
  ],
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER"
}
4

1 回答 1

2

我需要添加"contentType": "application/json"选项。

options = {
  "method" : "POST",
  "muteHttpExceptions": true,
  "headers": {
     'Authorization': 'Bearer ' +  theAccessTkn
   },
  "contentType": "application/json",
  "payload": JSON.stringify(payload)
};
于 2018-03-06T15:02:38.040 回答