node.js - 如何使用 node google client api 获取具有已获取 token 的用户配置文件?

标签 node.js google-api google-api-client

通过curl获取用户个人资料信息

curl -i https://www.googleapis.com/userinfo/v2/me -H "Authorization: Bearer a-google-account-access-token"

通过 Node https获取请求获取用户个人资料信息

const https = require('https');

function getUserData(accessToken) {
    var options = {        
                    hostname: 'www.googleapis.com',
                    port: 443,
                    path: '/userinfo/v2/me',
                    method: 'GET',
                    json: true,
                    headers:{
                        Authorization: 'Bearer ' + accessToken            
                   }
            };
    console.log(options);
    var getReq = https.request(options, function(res) {
        console.log("\nstatus code: ", res.statusCode);
        res.on('data', function(response) {
            try {
                var resObj = JSON.parse(response);
                console.log("response: ", resObj);
            } catch (err) {
                console.log(err);
            }
        });
    });

    getReq.end();
    getReq.on('error', function(err) {
        console.log(err);
    }); 

}

var token = "a-google-account-access-token";
getUserData(token)

我如何使用这个 google node api client library获取用户个人资料信息前提是我已经拥有访问 token ?我可以使用上面的代码来获取配置文件,但我认为使用 google api 库可能会更好,但我不知道如何使用这个 Node google api 客户端库来做到这一点。

通过玩这个playground可以获得一个临时的访问 token

最佳答案

您可以使用 the google node API client library 检索用户个人资料.在这种情况下,请检索作为 https://www.googleapis.com/auth/userinfo.profile 范围的访问 token 和刷新 token 。示例脚本如下。使用本示例时,请设置您的ACCESS TOKEN。

示例脚本:

var google = require('googleapis').google;
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2();
oauth2Client.setCredentials({access_token: 'ACCESS TOKEN HERE'});
var oauth2 = google.oauth2({
  auth: oauth2Client,
  version: 'v2'
});
oauth2.userinfo.get(
  function(err, res) {
    if (err) {
       console.log(err);
    } else {
       console.log(res);
    }
});

结果:

{
  id: '#####',
  name: '#####',
  given_name: '#####',
  family_name: '#####',
  link: '#####',
  picture: '#####',
  gender: '#####',
  locale: '#####'
}

如果我误解了你的问题,我很抱歉。

关于node.js - 如何使用 node google client api 获取具有已获取 token 的用户配置文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46780218/

相关文章:

javascript - 使用 knex.js 从关联表中删除数据

node.js - Mongoose find 和 findOne 中间件不工作

javascript - 如何使用 Mongoose 更新嵌套对象

node.js - 如何创建临时文件并将内容放入其中?

java - 如何在 Calendar Api 中禁用 Google 的 “Video Call” 默认值?

javascript - 从YouTube用户名获取YouTube个人资料图标

android - Google+登录跨客户端(android/web)身份验证

javascript - 可以通过 AJAX 使用 Google map /地点 'autocomplete' API 吗?

google-api-client - Google Slides API,图像在幻灯片上的定位

android - javax.net.ssl.SSLHandshakeException : Remote host closed connection during handshake while inserting rows in bigquery