Google Analytics API批量请求报错求助:TypeError及方法缺失问题
解决Google Analytics Reporting API V4批量请求的两类错误
我来帮你拆解下这两个错误的原因,再给出修正后的完整代码:
错误1:Cannot read property 'request' of undefined
这个问题出在你页面加载后立刻调用了analyticsReportRequest函数——此时用户还没完成登录,Google的API客户端gapi.client还没初始化完成,自然找不到request方法。所有和API请求相关的操作都必须等用户登录成功后再执行。
错误2:Batch entry is missing a request method
你把analyticsReportRequest调用后返回的Promise对象传给了batch.add(),但batch.add()需要的是未执行的请求配置对象,不是已经触发请求后返回的Promise。
修正后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Batching test</title> <meta name="google-signin-client_id" content="<MyID>"> <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly"> <!-- Load the JavaScript API client and Sign-in library. --> <script src="https://apis.google.com/js/client:platform.js"></script> </head> <body> <h1>Hello Analytics Reporting API V4</h1> <!-- The Sign-in button. This will run `batchExecution()` on success. --> <p class="g-signin2" data-onsuccess="batchExecution"></p> <script> const VIEW_ID = '3213999'; const sessionsM = 'ga:sessions'; const transactionsM = 'ga:transactions'; // 只生成请求配置,不直接执行请求 function createReportRequest(metric) { return { path: '/v4/reports:batchGet', root: 'https://analyticsreporting.googleapis.com/', method: 'POST', body: { reportRequests: [ { viewId: VIEW_ID, dateRanges: [ { startDate: '7daysAgo', endDate: 'today' } ], metrics: [ { expression: metric } ] } ] } }; } function batchExecution() { // 登录成功后再初始化批量请求 const batch = gapi.client.newBatch(); // 给每个批量请求添加独立回调 batch.add(createReportRequest(sessionsM), { callback: (response) => displayResults('用户会话报告', response.result) }); batch.add(createReportRequest(transactionsM), { callback: (response) => displayResults('交易数据报告', response.result) }); // 执行批量请求 batch.execute().catch(console.error); } function displayResults(reportName, result) { const formattedJson = `${reportName}:\n${JSON.stringify(result, null, 2)}\n\n`; document.getElementById('query-output').value += formattedJson; } </script> <!-- The API response will be printed here. --> <textarea cols="80" rows="20" id="query-output"></textarea> </body> </html>
关键修改点说明
- 把原有的
analyticsReportRequest改成createReportRequest,只返回请求配置对象,不直接触发请求,适配batch.add()的要求。 - 所有请求创建和批量执行逻辑都移到
batchExecution()函数内——这个函数是用户登录成功后才触发的,此时gapi.client已经完全初始化,不会再出现undefined问题。 - 给每个批量请求添加独立回调,分别处理两个报告的结果,同时修改
displayResults实现结果追加,避免覆盖。 - 修正了你原代码里的拼写错误:
choseMetric改成了正确的变量名(现在统一用metric)。
内容的提问来源于stack exchange,提问作者Joaquín Morales Luque
相关产品推荐
相关产品推荐

