在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代理,以便更好地管理网络请求。选择适合你需求的方法进行配置即可。