温馨提示×

centos nodejs怎么配代理

小樊
34
2026-09-11 18:24:03
栏目: 编程语言

在 CentOS 上给 Node.js 配置代理,通常有几种场景,下面按常见用法给你说明:


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

如果你是在 CentOS 上用 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://username:password@127.0.0.1:7890
npm config set https-proxy http://username:password@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:通过环境变量(推荐)

export HTTP_PROXY=http://127.0.0.1:7890
export HTTPS_PROXY=http://127.0.0.1:7890
node app.js

永久生效(写入环境变量):

echo 'export HTTP_PROXY=http://127.0.0.1:7890' >> ~/.bashrc
echo 'export HTTPS_PROXY=http://127.0.0.1:7890' >> ~/.bashrc
source ~/.bashrc

方式 2:在 Node.js 代码中使用代理(请求层面)

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 })
  .then(res => console.log(res.data));

http / https 请求

const http = require('http');
const url = require('url');

const options = {
  host: '127.0.0.1',
  port: 7890,
  method: 'CONNECT',
  path: 'api.github.com:443'
};

三、为 yarn 配置代理

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

四、CentOS 系统级代理(影响整体)

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 版本是否较老

公司内网证书问题

npm config set strict-ssl false

如果你能说明:

  • npm 安装慢
  • 还是 Node 请求接口走代理
  • 代理类型(Squid / Clash / 公司代理)

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

0