Appscript 中的授权请求标头

时间:2021-05-24 13:10:53

标签: javascript google-apps-script

我需要在 Appscript 中调用 API 数据 我有令牌:ZjA2YmYwNjYtNzgxYy00ZThjLWFjZjktMjEwYjM1O 我有网址:https://webexapis.com/v1/devices

如何使用链接验证令牌。 如果我只调用 URL,我会收到以下错误

{"message":"The request requires a valid access token set in the Authorization request header.","errors":[{"description":"The request requires a valid access token set in the Authorization request header."}],"trackingId":"ROUTER_60ABA481-B37E-01BB-03DC-0AFDE82A03DC"}

1 个答案:

答案 0 :(得分:2)

Auth token 需要放在 header 中:

function makeRequest_(po) {
  var options,r;

  /*
    po - A JSON object with the following settings
    po.url - The url to make the request to
    po.token - The Auth Token
    po.method - POST or GET etc
  */
  
  if (!po.url) {
    console.error('No URL passed in. Parameters:' + JSON.stringify(po));
    return;
  }

  options = {};
  options.method = po.method;
  options.headers = {Authorization: 'Bearer ' + po.token};
  options.muteHttpExceptions = true;//Make sure this is always set

  r = UrlFetchApp.fetch(po.url, options);

  if (!r) {
    console.error('ERROR - getting response' );
    return;
  }
  
  //Logger.log('r.getResponseCode(): ' + r.getResponseCode());

  if (r && r.getResponseCode() !== 200) {//There should always be a response unless the
    //Fetch call failed

    var arg = po ? JSON.stringify(po) :"po not passed in";
    Logger.log('ERROR ' + r + '\npo:' + arg);

    return false;
  }
  
  //Logger.log('r: ' + r)
  return r;

}