如何使用 Javascript 将 API 调用发送到具有多个指标的 Google Analytics API

How to send API call to the Google Analytics API with multiple metrics using Javascript

我正在使用 Node.js 和 Javascript 对 Google 分析 API 进行 API 调用。

const result = await google.analytics("v3").data.ga.get({
      ...defaults,
      "start-date" : "2019-01-01",
      "end-date" : "2019-02-01",
      metrics: ["ga:users", "ga:pageviews"]
    });

当我只使用 1 个参数作为参数时效果很好。但是当我像这样创建一组指标时,它只对其中一个指标做出响应。文档说实际上我可以一次发送多个指标,但我不知道如何使用 JSON 对象来做到这一点。我应该怎么做?

Google analytics api v3 中的指标参数不是数组而是字符串

 metrics: "ga:users, ga:pageviews"

Google 分析 api v4

您可能需要考虑更新到更新版本的 api

Hello analytics v4

<!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>