Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NestJS 中如何配置正向代理 #48

Open
ChuChencheng opened this issue Jun 1, 2023 · 0 comments
Open

NestJS 中如何配置正向代理 #48

ChuChencheng opened this issue Jun 1, 2023 · 0 comments
Labels

Comments

@ChuChencheng
Copy link
Owner

ChuChencheng commented Jun 1, 2023

背景

NestJS 应用内部请求了外部的 HTTP API ,由于某些原因需要代理。由于 NestJS 的 HttpModule 内部使用的是 axios ,因此直接找到官网搜 proxy 。

本篇重点记录使用环境变量的方式,可不修改代码。

Axios 配置代理

在其官方文档中,说明了两种配置代理的方式:

  1. 在 Request Config 中传入 proxy 配置
  2. 使用 http_proxy, https_proxy, no_proxy 环境变量

第一种方式比较明确,在 NestJS 中,在引入 HttpModule 时使用 register 传入配置即可

HttpModule.register({
  proxy: {},
})

但是这种配置方式直接侵入了代码,怎么说都得再发个版,不如看看用环境变量如何解决。

Proxy 环境变量

在 Axios 官网中看到的三个环境变量,有许多工具跟语言都支持,例如 curl, Go 等。

不过这几个环境变量没有一个固定的标准,因此各个程序对它们的支持略微有些差异。

例如在这篇文章中,就讲述了由于 Ruby 跟 Go 对于 no_proxy 支持上的差异而导致的问题:

We need to talk: Can we standardize NO_PROXY?

不过在此我只记录如何在 NestJS 应用中配置,就不去深究它们之间的差异了。

Axios 中对 http_proxy 等环境变量的支持

package.json 中可以看到这么一个库用于读取 proxy 环境变量:

proxy-from-env

可以看到这个库支持 http_proxy, https_proxy, no_proxyall_proxy (实际上是取了 ${protocol}_proxy ,因此 ftp, ws 之类的协议也是支持的,只要 Axios 能请求)

对于大小写的环境变量都支持了,且优先小写,可见代码

NestJS 配置正向代理

看到这里,配置方式很明确了,按需加上 http_proxy 等环境变量即可,例如:

http_proxy=http://username:password@example.com:8080
https_proxy=http://username:password@example.com:8080

对应 axios 中的 proxy 配置:

proxy: {
  protocol: 'http',
  host: 'example.com',
  port: 8080,
  auth: {
    username: 'username',
    password: 'password'
  }
}

优缺点

优点:

  • 对代码无侵入,无需修改代码发版

缺点:

  • 虽然可以覆盖大部分场景,但是对于只需要代理某几个域名的情况,用环境变量貌似没有可以配置的方式,或许需要代理服务器那边去处理?
  • 如果环境变量会被多个应用读取,需要注意不同程序工具之间对于 http_proxy 环境变量读取的差异,比如支持情况,大小写等
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant