因为开发习惯,一直依赖使用代理工具, mock 各种数据 ,直观查看响应数据,以及各个环境host切换
浏览器端,借助swithOmge + lightproxy 可以很方便抓包
在nodejs服务端开发过程中,也可以通过各种目的实现抓包
在基于eggjs的工程,官方提供了代理配置,也很容易代理抓包,文档
nextjs好像没有提供对应配置开关。但是可以通过以下办法实现代理
参考:https://gist.github.com/simonhaenisch/7ffcd9833ddaf4236e036d33d018dd2f

polyfills node环境fetch

nextjs 在服务端polyfills fetch, 文档

In addition to fetch() on the client-side, Next.js polyfills fetch() in the Node.js environment. You can use fetch() in your server code (such as getStaticProps/getServerSideProps) without using polyfills such as isomorphic-unfetch or node-fetch.

但是看文档源码,其实也是引入node-fetch
image.png
nextjs/packages/next/server/node-polyfill-fetch.js
从全局__NEXT_HTTP_AGENT获取代理agent,组装fetchWithAgent,赋值给全局变量fetch,所以可以直接在nextjs getServisideprops中直接使用fetch

  1. import fetch, {
  2. Headers,
  3. Request,
  4. Response,
  5. } from 'next/dist/compiled/node-fetch'
  6. // Polyfill fetch() in the Node.js environment
  7. if (!global.fetch) {
  8. const agent = ({ protocol }) =>
  9. protocol === 'http:' ? global.__NEXT_HTTP_AGENT : global.__NEXT_HTTPS_AGENT
  10. const fetchWithAgent = (url, opts, ...rest) => {
  11. if (!opts) {
  12. opts = { agent }
  13. } else if (!opts.agent) {
  14. opts.agent = agent
  15. }
  16. return fetch(url, opts, ...rest)
  17. }
  18. global.fetch = fetchWithAgent
  19. global.Headers = Headers
  20. global.Request = Request
  21. global.Response = Response
  22. }

node-fetch

A light-weight module that brings Fetch API to Node.js.
支持 Custom Agent

In addition, the agent option accepts a function that returns http(s).Agent instance given current URL, this is useful during a redirection chain across HTTP and HTTPS protocol.

也就是nextjs上面的fetchWithAgent

http-proxy-agent

This module provides an http.Agent implementation that connects to a specified HTTP or HTTPS proxy server, and can be used with the built-in http module.

var agent = new HttpProxyAgent(proxy); proxy可以是string或者object

nextjs配置代理

image.png

  1. import ProxyAgent from 'https-proxy-agent'
  2. if (typeof window === 'undefined') {
  3. global.__NEXT_HTTP_AGENT = new ProxyAgent('http://127.0.0.1:12888')
  4. }

这是就能抓到包了
image.png

待实践

其实全局的agent是通过读取next.config.js 中的 httpAgentOptions 来创建的,但是还没找到需要配置的key
参考:
https://nodejs.org/api/http.html#new-agentoptions new Agent

https://github.com/vercel/next.js/blob/6b8e499c7bf13914cca92f9da1737d358133ee20/packages/next/server/config.ts#L869
image.png