Google API批处理返回401

时间:2018-11-14 05:35:26

标签: javascript google-api google-api-client gapi google-api-js-client

一次批处理两个或多个请求将导致每个请求401。

const batch = gapi.client.newBatch();
batch.add(gapi.client.drive.files.list());
batch.add(gapi.client.drive.files.list());
batch.then((e) => {
  console.log(e);
});

错误是:

{
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "authError",
    "message": "Invalid Credentials",
    "locationType": "header",
    "location": "Authorization"
   }
  ],
  "code": 401,
  "message": "Invalid Credentials"
 }
}

仅使用一个 batch.add 即可正常运行。这对我来说没有任何意义。

为什么?我该怎么办?

1 个答案:

答案 0 :(得分:-1)

直接来自文档handle errors

  

401:无效的凭据   授权标头无效。您正在使用的访问令牌已过期或无效。

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "authError",
        "message": "Invalid Credentials",
        "locationType": "header",
        "location": "Authorization",
      }
    ],
    "code": 401,
    "message": "Invalid Credentials"
  }
}
  

建议的操作:使用寿命长的刷新令牌刷新访问令牌。如果失败,请按照Authorizing Your App with Google Drive中的说明引导用户通过OAuth流程。

Batch文档。

var searchRequest = function(name) {
  return gapi.client.request({
    'path': 'plus/v1/people',
    'params': {'query': name}
   });
};
var searchAlvin = searchRequest('Alvin');
var searchSimon = searchRequest('Simon');

// Adding just the request
batch.add(searchAlvin);
// Adding the request with an ID
batch.add(searchSimon, {'id': 'searchSimon'});