温馨提示×

ubuntu nodejs怎么配代理

小樊
40
2026-10-04 15:40:50
栏目: 编程语言

在 Ubuntu 上给 Node.js 配置代理,常见有系统环境变量代理、npm 代理、yarn/pnpm 代理、以及代码里使用代理几种方式。下面按场景说明。


一、为 npm 配置代理(最常用)

1. 设置 HTTP / HTTPS 代理

npm config set proxy http://127.0.0.1:7890
npm config set https-proxy http://127.0.0.1:7890

2. 取消代理

npm config delete proxy
npm config delete https-proxy

3. 查看当前配置

npm config get proxy
npm config get https-proxy

二、为 yarn 配置代理

yarn config set proxy http://127.0.0.1:7890
yarn config set https-proxy http://127.0.0.1:7890

取消:

yarn config delete proxy
yarn config delete https-proxy

三、为 pnpm 配置代理

pnpm config set proxy http://127.0.0.1:7890
pnpm config set https-proxy http://127.0.0.1:7890

四、为 Node.js 运行环境配置代理(系统级)

1. 临时生效(当前终端)

export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890

2. 永久生效

sudo nano ~/.bashrc

添加:

export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890

保存后:

source ~/.bashrc

五、Node.js 代码中使用代理

1. 使用 axios

const axios = require('axios');
const httpsProxyAgent = require('https-proxy-agent');

const agent = new httpsProxyAgent('http://127.0.0.1:7890');

axios.get('https://api.github.com', { httpsAgent: agent });

2. 使用 node-fetch

const fetch = require('node-fetch');
const ProxyAgent = require('proxy-agent');

fetch('https://api.github.com', {
  agent: new ProxyAgent('http://127.0.0.1:7890')
});

六、常见问题

1. 公司代理需要账号密码

http://username:password@127.0.0.1:7890

2. 使用私有镜像(如淘宝)

npm config set registry https://registry.npmmirror.com

3. 代理不生效

  • 确认端口是否正确
  • 确认代理软件已运行
  • 使用 curl -v https://npmjs.org 测试

如果你能说明是 npm 安装慢 / Node 服务访问外网 / Docker 内 Node 哪种场景,我可以给你更精确的配置方案。

0 踩