如何使用节点谷歌客户端 api 获取已获取令牌的用户个人资料? [英] How to use the node google client api to get user profile with already fetched token?

查看:17
本文介绍了如何使用节点谷歌客户端 api 获取已获取令牌的用户个人资料?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过 curl

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

通过节点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("
status 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 客户端库来获取用户个人资料信息前提是我已经拥有访问令牌?我可以使用上面的代码来获取配置文件,但我认为使用 google api 库来执行此操作可能会更好,但我无法弄清楚如何使用此节点 google api 客户端库来执行此操作.

How can I use this google node api client library to get the user profile info provided that I already have the access token? I can use the code above to get the profile but I thought it's probably better off to use the google api library to do it, but I can't figure out how to do that using this node google api client library.

可以通过玩这个playground

推荐答案

您可以使用 google node API 客户端库.在这种情况下,请检索访问令牌和刷新令牌作为 https://www.googleapis.com/auth/userinfo.profile 的范围.示例脚本如下.使用本示例时,请设置您的访问令牌.

You can retrieve the user profile using the google node API client library. In this case, please retrieve the access token and refresh token as the scope of https://www.googleapis.com/auth/userinfo.profile. The sample script is as follows. When you use this sample, please set your 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: '#####'
}

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

If I misunderstand your question, I'm sorry.

这篇关于如何使用节点谷歌客户端 api 获取已获取令牌的用户个人资料?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆