在 CentOS 上给 Node.js 配置代理,常见有几种场景,下面按使用方式给你说明,你可以按需选。
npm config set proxy http://127.0.0.1:7890
npm config set https-proxy http://127.0.0.1:7890
npm config set proxy http://user:pass@127.0.0.1:7890
npm config set https-proxy http://user:pass@127.0.0.1:7890
npm config get proxy
npm config get https-proxy
npm config delete proxy
npm config delete https-proxy
在运行 Node 前设置:
export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
node app.js
或者在 .bashrc / .profile 中永久生效:
echo 'export HTTP_PROXY=http://127.0.0.1:7890' >> ~/.bashrc
echo 'export HTTPS_PROXY=http://127.0.0.1:7890' >> ~/.bashrc
source ~/.bashrc
⚠️ 注意:
Node.js 原生 http/https 模块不会自动读取这些变量,只有部分库支持(如 axios + https-proxy-agent)
const axios = require('axios');
const { HttpsProxyAgent } = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://127.0.0.1:7890');
axios.get('https://api.example.com', { httpsAgent: agent })
.then(res => console.log(res.data));
安装依赖:
npm install axios https-proxy-agent
yarn config set proxy http://127.0.0.1:7890
yarn config set https-proxy http://127.0.0.1:7890
pnpm config set proxy http://127.0.0.1:7890
pnpm config set https-proxy http://127.0.0.1:7890
可能是:
可测试:
curl -x http://127.0.0.1:7890 https://registry.npmjs.org
如果你能告诉我:
我可以给你更精确的配置方案。