1

我的应用程序在同一个身份验证初始化下使用多个 API 都成功 - 除了应用程序脚本执行 API 引发错误代码 401 并显示以下消息:“请求缺少所需的身份验证凭据。预期的 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据. 见https://developers.google.com/identity/sign-in/web/devconsole-project。”

我正在使用相同的 Google Cloud 项目 ID,正确设置了 Apps Script 函数 API 可执行文件。发送电子邮件 API 和从 Drive API 获取文件运行良好。除了这个。我在本地主机上运行它们。

我将精简代码以仅放大我认为可能是问题的最相关部分。

<script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer></script>

<script>
window.onLoadCallback = function(){
gapi.load('auth2', initSigninV2);
};

function initSigninV2() {
    gapi.auth2.init({
            apiKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
            discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/drive/v3/rest","https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest","https://script.googleapis.com/$discovery/rest?version=v1"],
            clientId: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com',
            scope: 'https://www.googleapis.com/auth/drive'+' https://www.googleapis.com/auth/gmail.send'+' https://www.googleapis.com/auth/script.scriptapp'
    }).then(function (authInstance) {
        if(!gapi.auth2.getAuthInstance().isSignedIn.get()) {
        gapi.auth2.getAuthInstance().signIn();

        }
                 // Listen for sign-in state changes.
          gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);

          // Handle the initial sign-in state.
          updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());

    });
}

</script>

这是失败的功能:

function appScript(callback, data, field, dl) {
    var scriptId = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    var request = {
        'function': 'doPost',
        'parameters': {'data':JSON.stringify(data)}
    };
    var headers = getClientRequestHeaders();
    console.log(headers);

    gapi.client.request({
        'root': 'https://script.googleapis.com',
        'path': 'v1/scripts/' + scriptId + ':run',
        'method': 'POST',
        'headers': headers,
        'body': request
    }).then(function (response) {
            console.log(response);
    //      callback(response.fileid, response.id, field);
    //      if (dl) {
    //      dl(response.fileid);
    //      }
        });
}
4

1 回答 1

0

我找到了解决方案:代码 401 正在返回,因为我没有正确的范围,我进入我的 Google Apps 脚本 > 文件 > 属性 > 范围以查看我真正需要的范围是什么,结果发现我缺少一个范围.

我添加了这个,一切都运行得很完美。

于 2018-12-23T15:44:52.907 回答