如何设置节点http代理来拦截特定的请求/响应?

Tho*_*mas 6 https http-proxy node.js puppeteer

我正在制作一个加载网页的 nodejs pupeteer 应用程序。在该页面中,加载了许多资源。用于拦截请求/响应的 pupeteer API 似乎不适用于所有资源,所以我想使用 http 代理。

我想在我的代理中拦截特定的请求/响应。如果远程服务器发回内容的第一行是单词“cat”的响应,那么我想在将响应转发回客户端之前控制台.记录该资源 URL。该请求可以使用 https。我怎样才能实现这样的目标?

Pte*_*tyl 3

https://anyproxy.io/en/#use-anyproxy-as-an-npm-module

首先安装AnyProxy

对于 Debian / Ubuntu 用户,首先执行以下操作:

sudo apt-get install nodejs-legacy
Run Code Online (Sandbox Code Playgroud)

然后安装AnyProxy:

npm install -g anyproxy
Run Code Online (Sandbox Code Playgroud)

您需要编写一条规则来拦截以 cat 和 console.log 开头的响应。所以也许是这样的:

// file: sample.js
module.exports = {
  summary: 'a rule to log responses starting with cat',
  *beforeSendResponse(requestDetail, responseDetail) {
    if responseDetail.body.startsWith("cat "){
         console.log(responseDetail.body);
    }
  },
};
Run Code Online (Sandbox Code Playgroud)

AnyProxy默认不拦截https请求。要查看解密信息,您必须配置 CA 证书。

anyproxy-ca #generate root CA. manually trust it after that.
anyproxy --intercept --rule sample.js #launch anyproxy and intercept all https traffic, and use sample.js rule
Run Code Online (Sandbox Code Playgroud)

根据您的设置,您可能需要执行其他配置操作,但是一旦设置完毕,编写拦截响应的规则似乎很简单。