美文网首页
googleapis 谷歌统计 nodejs 遇到 ECONNR

googleapis 谷歌统计 nodejs 遇到 ECONNR

作者: FeinZee | 来源:发表于2020-09-02 15:50 被阅读0次

解决方案在最后,中间是一长串心路历程。

最近用nodejs写一个后端,想访问googleapis来获取某一网页的浏览量等。
代码本身很简单:

const { google } = require("googleapis");
const key = require("../config/key.json"); // 创建凭据生成的json密钥
const VIEW_ID = "ga:xxxxxxxx"; // 自己的viewID

const jwtClient = new google.auth.JWT(
  key.client_email,
  null,
  key.private_key,
  [
    "https://www.googleapis.com/auth/analytics",
    "https://www.googleapis.com/auth/analytics.readonly",
  ],
  null
);


async function queryData(jwtClient) {
  let options = {
    auth: jwtClient,
    ids: VIEW_ID,
    metrics: "ga:pageviews",
    dimensions: "ga:date",
    "start-date": "30daysAgo", //查询时间区间
    "end-date": "today"
  };

  return google
    .analytics("v3")
    .data.ga.get(options)
    .then((res) => {
      console.log(res.data);
    });
}

queryData(jwtClient);

但获取不到数据,一直得到错误:

FetchError: request to https://www.googleapis.com/oauth2/v4/token failed, reason: read ECONNRESET

我已经开了代理,谷歌统计的网页也上得去,咋不行呢?可愁死我了。一直以为是自己代码写得有问题。
后来我做了一个尝试:

  1. 这个网址https://ga-dev-tools.appspot.com/query-explorer/#report-start 提供了访问googleapis获取数据的工具,点击 Run Query 按钮后。
  2. 出现 API Query URI, 勾选上 include current access_token,然后复制这个uri,直接放到浏览器网址中访问。
  3. 结果是正常访问到数据。
  4. 在node环境用request去访问这个uri。
  5. 啊哦~还是ECONNREST。
    到这里,解决思路大概有了,导师也指点我,问题是出现在网络代理上了。node运行的时候,应该是没走代理。那我自然是试着搜索node如何设置代理啦,我就用
npm config set proxy = "http://proxyhost:port"

但没成功,这一点我也没想明白。
P.S. 控制面板-网络和Inernet选项-Internet选项-选择标签[连接]-打开右下角[局域网设置]就能在下方的[代理服务器]区域看到自己的代理host和port了。一般可能代理模式会是智能分流,有时候是这样的,那就模式改为全局分流就能看到了。

image.png

最后,解决方案来啦,在代码中加入两行:

const { google } = require("googleapis");
process.env.HTTPS_PROXY = 'http://proxyhost:port'; // 就是这里
google.options({ proxy: 'http://proxyhost:port' }); // 和这里

指导老师说有googleapis可以设置代理:https://www.npmjs.com/package/googleapis#using-a-proxy
然后我搜到了github的issues https://github.com/googleapis/google-api-nodejs-client/issues/64 里的解决方案。
后来我发现,只用下面一行也可以,但是我的request不是https的吗?存疑orz

process.env.HTTP_PROXY = 'http://proxyhost:port'; // 为 non-SSL request做代理

就是这样。两行代码,卡了两天半。当数据终于获取到的时候,那种无敌的快乐,送我一个男朋友都比不上。

相关文章

网友评论

      本文标题:googleapis 谷歌统计 nodejs 遇到 ECONNR

      本文链接:https://www.haomeiwen.com/subject/dfrwsktx.html