Google Analytics API 单击后 OAuth "Allow" 无法连接到本地主机

Google Analytics API OAuth after clicking "Allow" cannot connect to local host

我正在尝试获取 Google Analytics API 的访问令牌。

在开发人员控制台中创建项目并授予对 Analytics API 的访问权限后,我到达了 "create credentials" 步骤并为 Web 应用程序创建了新凭据。

在这些凭据上,我将 Javascript 来源设置为 http://localhost:8080 and also http://localhost:5000. Then I set authorized redirect URIs to http://localhost:8080/oauth2callback as well as http://localhost:5000/oauth2callback

然后,当我尝试授权时,我被要求输入我的 clientId 和密码,我这样做了,然后新的浏览器选项卡打开,我被要求选择一个帐户,然后 select "Allow".

然后,当我单击 "Allow" 时,我将转到此页面:

我还尝试为 "other" 类型的应用程序创建凭据,但发生了完全相同的事情。

我在 stack overflow 上发现了很多关于此的帖子,但 none 的答案能够解决我的问题。不确定要提供哪些其他信息。我什至尝试清除历史记录并使用不同的浏览器,但都没有成功。

如何使用 OAuth 将我的应用程序授权给 Google Analytics?

此问题与本地主机或您的重定向 uris 或 JavaScript 来源无关。问题是您的代码未设置为处理来自身份验证服务器的回调。如果您已经发布了您的代码,那将会有所帮助,这样就很难知道问题出在哪里。

你应该在这里查看官方示例Hello analytics js tutorial

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
  <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>

<h1>Hello Analytics Reporting API V4</h1>

<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>

<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>

<script>
  // Replace with your view ID.
  var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';

  // Query the API and print the results to the page.
  function queryReports() {
    gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com/',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [
              {
                startDate: '7daysAgo',
                endDate: 'today'
              }
            ],
            metrics: [
              {
                expression: 'ga:sessions'
              }
            ]
          }
        ]
      }
    }).then(displayResults, console.error.bind(console));
  }

  function displayResults(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  }
</script>

<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>

</body>
</html>