在 Ubuntu 上给 Node.js 配置代理,常见有系统环境变量代理、npm 代理、yarn/pnpm 代理、以及代码里使用代理几种方式。下面按场景说明。
npm config set proxy http://127.0.0.1:7890
npm config set https-proxy http://127.0.0.1:7890
npm config delete proxy
npm config delete https-proxy
npm config get proxy
npm config get https-proxy
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 config set proxy http://127.0.0.1:7890
pnpm config set https-proxy http://127.0.0.1:7890
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
sudo nano ~/.bashrc
添加:
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
保存后:
source ~/.bashrc
axiosconst 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 });
node-fetchconst fetch = require('node-fetch');
const ProxyAgent = require('proxy-agent');
fetch('https://api.github.com', {
agent: new ProxyAgent('http://127.0.0.1:7890')
});
http://username:password@127.0.0.1:7890
npm config set registry https://registry.npmmirror.com
curl -v https://npmjs.org 测试如果你能说明是 npm 安装慢 / Node 服务访问外网 / Docker 内 Node 哪种场景,我可以给你更精确的配置方案。