温馨提示×

centos nodejs如何配置代理

小樊
67
2026-09-14 23:16:48
栏目: 编程语言

在 CentOS 上配置 Node.js 的代理,通常有 系统级代理、npm 代理、Node 应用代码级代理 几种方式,下面按常见场景说明。


一、为 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 get proxy
npm config get https-proxy

3. 取消代理

npm config delete proxy
npm config delete https-proxy

二、为 yarn 配置代理(如使用 yarn)

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

三、为 Node.js 运行环境配置代理(系统环境变量)

适用于 fetch、axios、部分 CLI 工具。

export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890

永久生效(推荐)

编辑:

vi /etc/profile

添加:

export http_proxy=http://127.0.0.1:7890
export https_proxy=http://127.0.0.1:7890

然后:

source /etc/profile

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

1. 使用 axios + http-proxy-agent

npm install 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));

五、Docker / PM2 场景(补充)

PM2

pm2 startup
pm2 env myapp http_proxy http://127.0.0.1:7890

Docker

ENV http_proxy=http://host.docker.internal:7890
ENV https_proxy=http://host.docker.internal:7890

六、常见问题

1. 公司内网代理需要账号

npm config set proxy http://user:pass@host:port

2. 私有仓库不走代理

npm config set noproxy "registry.npmjs.org,*.example.com"

如果你能说明:

  • 是 npm 安装慢
  • 还是 Node 应用访问外网失败
  • 或是否在 Docker / 服务器无桌面环境

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

0 踩