温馨提示×

centos怎么配nodejs代理

小樊
49
2026-09-21 03:10:35
栏目: 编程语言

在 CentOS 上“配 Node.js 代理”通常有两种常见含义,我分别说明,你按需取用:


一、给 Node.js / npm 配置网络代理(访问外网)

如果你在 CentOS 上通过代理服务器访问互联网(比如公司内网),需要给 npm 或 Node 进程配置代理。

1️⃣ 配置 npm 代理

npm config set proxy http://代理IP:端口
npm config set https-proxy http://代理IP:端口

取消代理:

npm config delete proxy
npm config delete https-proxy

查看当前配置:

npm config get proxy

2️⃣ 配置 yarn 代理(如果用 yarn)

yarn config set proxy http://代理IP:端口
yarn config set https-proxy http://代理IP:端口

3️⃣ Node.js 运行时使用代理

如果 Node 程序本身要请求外网:

方式一:环境变量

export HTTP_PROXY=http://代理IP:端口
export HTTPS_PROXY=http://代理IP:端口
node app.js

方式二:代码中使用(如 axios)

const axios = require('axios');
const httpsProxyAgent = require('https-proxy-agent');

const agent = new httpsProxyAgent('http://代理IP:端口');

axios.get('https://api.example.com', { httpsAgent: agent });

二、用 Node.js 在 CentOS 上搭建反向代理(如 Nginx 替代)

如果你想用 Node.js 做代理服务器(反向代理前端/后端服务):

示例:Node + http-proxy

npm install http-proxy
const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer();

http.createServer((req, res) => {
  proxy.web(req, res, {
    target: 'http://127.0.0.1:3000'
  });
}).listen(80);

访问 http://服务器IP → 转发到本地 3000 端口。


三、常见场景建议

  • ✅ 只是装包慢 → 配 npm 代理或用国内镜像
  • ✅ 正式服务 → 推荐 Nginx 反向代理 + Node 后端
  • ✅ 内网穿透 → Node 代理或 frp / Nginx

如果你能说清楚:

  • 是 npm 装包代理
  • 还是 Node 做反向代理
  • 还是 服务器出口代理

我可以给你更精确的配置示例。

0 踩