温馨提示×

centos nodejs怎样配代理

小樊
49
2026-09-27 00:45:48
栏目: 编程语言

在 CentOS 上给 Node.js 配置代理,常见有几种场景,下面按使用方式给你说明,你可以按需选。


一、为 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 set proxy http://user:pass@127.0.0.1:7890
npm config set https-proxy http://user:pass@127.0.0.1:7890

3️⃣ 查看当前配置

npm config get proxy
npm config get https-proxy

4️⃣ 取消代理

npm config delete proxy
npm config delete https-proxy

二、为 Node.js 运行环境配置代理(代码层面)

方式 1:使用环境变量(推荐)

在运行 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)


方式 2:在代码中使用代理(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.example.com', { httpsAgent: agent })
  .then(res => console.log(res.data));

安装依赖:

npm install axios https-proxy-agent

三、为 yarn 配置代理(如果用 yarn)

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

四、为 pnpm 配置代理

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

五、常见问题

❓ npm 还是连不上

可能是:

  • 代理端口不对
  • 防火墙拦截
  • 使用了公司代理,需要加账号密码

可测试:

curl -x http://127.0.0.1:7890 https://registry.npmjs.org

如果你能告诉我:

  • 你是 npm 装包慢,还是 Node 请求外部接口需要代理
  • 代理类型(Clash / Squid / 公司代理)

我可以给你更精确的配置方案。

0 踩