获取用户数据Gmail API-JS

时间:2019-03-16 22:30:03

标签: javascript google-app-engine gmail-api

我正在尝试验证用户身份并获取用户数据,例如姓名和电子邮件。 我从这里google开始关注文档。 这是我的身份验证代码:

function handleClientLoad() {
    gapi.load('client:auth2', initClient);
}

function initClient() {

// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = 
["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"];

// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = 'https://www.googleapis.com/auth/gmail.readonly';

    gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
    }).then(function (data) {
    }, function(error) {
    });
}

用户单击按钮时:

    if(!gapi.auth2.getAuthInstance().isSignedIn.get()){
        gapi.auth2.getAuthInstance().signIn();
    }

// user IS authenticated here
    var profile = gapi.auth2.getAuthInstance().currentUser.get();
    console.log('Email: ' + profile.getEmail());

当我console.log(gapi.auth2)时,我看到我有函数BasicProfile(),但是如果我使用gapi.auth2.BasicProfile().getEmail(),则会出现此错误:

  

cb = gapi.loaded_0:219未捕获的TypeError:无法读取null的属性'sub'       在Object.PG [作为BasicProfile](cb = gapi.loaded_0:219)

1 个答案:

答案 0 :(得分:0)

一种解决方案:

// The user is authenticated here
    gapi.client.gmail.users.getProfile({
        'userId': 'me'
    }).then(function(response) {
       console.log(response);
    });