【问题标题】:How do I use token to call Google API with node and express如何使用令牌通过 node 和 express 调用 Google API
【发布时间】:2019-09-21 17:56:30
【问题描述】:

我正在构建一个小型 Node/React 应用程序,我正在尝试实现 OAuth2 Google 以请求 Google Analytics API。我正在使用 Passport.js 来处理身份验证。

然后根据我对documentation 的理解,我需要use token to call Google API。我该怎么做呢?

我将令牌传递给变量:

router.get(
    "/auth/google/callback",
    passport.authenticate("google", { failureRedirect: "/error", session: false }),
    function(req, res) {
        var token = req.user.token;
        res.redirect("http://localhost:5000/?token=" + token);


    }
);

例如,我想做的是获取授权用户的所有视图(配置文件)的列表。 在此示例中如何传递令牌?

function listViews() {
  var request = gapi.client.analytics.management.profiles.list({
        accountId: '~all',
        webPropertyId: '~all'
  });
  request.execute(printViews);
}

我试过这个:

router.get('/getData', function(req, res) {
    googleAccounts.management.profiles.list(
      {
        accountId: '~all',
        webPropertyId: '~all'
      },
      (err, data) => {
        if (err) {
          console.error('Error: ' + err)
          res.send('An error occurred')
        } else if (data) {

          Console.log(data)

        }
      }
    )
})

但我有一个错误Error: Login Required.

【问题讨论】:

  • 你能提供更多关于gapigoogleAccounts的信息吗?这些是在哪里定义的?
  • googleAccounts 是用这个const googleAccounts = google.analytics('v3')定义的

标签: node.js express passport.js google-authentication


【解决方案1】:

要使用令牌,您可以在 api 调用之前设置它:

function listViews() {
  gapi.client.setToken{
    access_token: <token-here>
  })
  var request = gapi.client.analytics.management.profiles.list({
        accountId: '~all',
        webPropertyId: '~all'
  });
  request.execute(printViews);
}

Google API Javascript Client Reference

【讨论】:

    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2014-11-02
    • 2022-01-11
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多