【问题标题】:POST vs. GET request differences in Google Analytics API Version 4Google Analytics API 版本 4 中的 POST 与 GET 请求差异
【发布时间】:2016-06-29 19:53:47
【问题描述】:

Google Analytics v4 API 现在使用 POST 请求而不是 GET 请求。而且还没有好的 javascript 示例可供我学习。我得到的是空对象 Object { },但我确定数据在那里并且 ViewID 是正确的!

关于我做错了什么有什么建议吗?或者有什么我可以效仿的完全有效的例子吗?谢谢。

requestData = function () {
var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";

var params = {
    "reportRequests":[{
        "viewId":"12345678",
        "dateRanges":[{
            "startDate":"yesterday",
            "endDate":"today"
        }],
        "metrics":[{
          "expression":"ga:users"
        }],
        "dimensions": [{
          "name":"ga:pagePath"
        }]
    }]
}

$.ajax({       
    url: url,
    type: "POST",
    data: params,
    dataType: "json",
    success: function(results) {
        console.log(results)
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert('failed');
        alert(xhr.status);
        alert(thrownError);
    }
});

【问题讨论】:

标签: google-analytics-api


【解决方案1】:

我强烈建议您使用Google Javascript Client Library 来大大简化您的生活。有很多Code Samples 使用该库:

var DISCOVERY = 'https://analyticsreporting.googleapis.com/$discovery/rest';

// Load the API from the client discovery URL.
gapi.client.load(DISCOVERY).then(function() {

// Call the Analytics Reporting API V4 batchGet method.
gapi.client.analyticsreporting.reports.batchGet( {
  "reportRequests":[{
    "viewId":"12345678",
    "dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
    "metrics":[{"expression":"ga:users"}],
    "dimensions": [{"name":"ga:pagePath"}]
  }]
}).then(function(response) {
  var formattedJson = JSON.stringify(response.result, null, 2);
  document.getElementById('query-output').value = formattedJson;
}).then(null, function(err) {
  // Log any errors.
  console.log(err);
});

至于让 jQuery 工作,类似的问题被问到 nodejs 他们的解决方案是设置 content-type=application/json 幸运的是 Asked and answered 也是如此。

var url = "https://analyticsreporting.googleapis.com/v4/reports:batchGet?";

var data = {
  "reportRequests":[{
    "viewId":"12345678",
    "dateRanges":[{ "startDate":"7daysAgo", "endDate":"today"}],
    "metrics":[{"expression":"ga:users"}],
    "dimensions": [{"name":"ga:pagePath"}]
  }]
}

$.ajax({
  url: url,
  type: "POST",
  data: data,
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(results) {
    console.log(results)
  },
  error: function(xhr, ajaxOptions, thrownError) {
    alert('failed');
    alert(xhr.status);
    alert(thrownError);
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2016-08-25
    • 2019-01-22
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多