阅读量:2
在Ubuntu上配置Node.js代理可以帮助你在开发和生产环境中更好地管理网络请求。以下是一些常见的方法来配置Node.js代理:
方法一:使用环境变量
-
设置HTTP代理
export HTTP_PROXY=http://your-proxy-url:port export HTTPS_PROXY=https://your-proxy-url:port -
设置NO_PROXY 如果你需要排除某些域名或IP地址不通过代理,可以设置
NO_PROXY环境变量:export NO_PROXY=localhost,127.0.0.1,.example.com -
在Node.js应用中使用 你可以在Node.js应用中读取这些环境变量:
const http = require('http'); const options = { hostname: 'example.com', port: 80, path: '/', method: 'GET', headers: { 'Proxy-Authorization': 'Basic ' + Buffer.from('username:password').toString('base64') } }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); req.end();
方法二:使用http-proxy-agent模块
-
安装
http-proxy-agent模块npm install http-proxy-agent -
在Node.js应用中使用
const http = require('http'); const HttpProxyAgent = require('http-proxy-agent'); const proxyAgent = new HttpProxyAgent({ host: 'your-proxy-url', port: 'port' }); const options = { hostname: 'example.com', port: 80, path: '/', method: 'GET', agent: proxyAgent }; const req = http.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); req.end();
方法三:使用https-proxy-agent模块
如果你需要代理HTTPS请求,可以使用https-proxy-agent模块:
-
安装
https-proxy-agent模块npm install https-proxy-agent -
在Node.js应用中使用
const https = require('https'); const HttpsProxyAgent = require('https-proxy-agent'); const proxyAgent = new HttpsProxyAgent({ host: 'your-proxy-url', port: 'port' }); const options = { hostname: 'example.com', port: 443, path: '/', method: 'GET', agent: proxyAgent }; const req = https.request(options, (res) => { console.log(`STATUS: ${res.statusCode}`); res.on('data', (chunk) => { console.log(`BODY: ${chunk}`); }); }); req.on('error', (e) => { console.error(`problem with request: ${e.message}`); }); req.end();
方法四:使用noproxy配置
如果你使用的是Node.js的HTTP/HTTPS模块,并且想要在代码中直接配置代理,可以使用noproxy选项:
const http = require('http');
const HttpsProxyAgent = require('https-proxy-agent');
const proxyAgent = new HttpsProxyAgent({
host: 'your-proxy-url',
port: 'port'
});
const options = {
hostname: 'example.com',
port: 443,
path: '/',
method: 'GET',
agent: proxyAgent,
noproxy: 'localhost,127.0.0.1,.example.com'
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();
通过以上方法,你可以在Ubuntu上配置Node.js代理,以便更好地管理网络请求。选择适合你需求的方法进行配置即可。
以上就是关于“如何在Ubuntu上配置Node.js代理”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm