在 CentOS 上“配 Node.js 代理”通常有两种常见含义,我分别说明,你按需取用:
如果你在 CentOS 上通过代理服务器访问互联网(比如公司内网),需要给 npm 或 Node 进程配置代理。
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
yarn config set proxy http://代理IP:端口
yarn config set https-proxy http://代理IP:端口
如果 Node 程序本身要请求外网:
export HTTP_PROXY=http://代理IP:端口
export HTTPS_PROXY=http://代理IP:端口
node app.js
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 做代理服务器(反向代理前端/后端服务):
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 端口。
如果你能说清楚:
我可以给你更精确的配置示例。