Node.js写采集脚本或者API代理——axios、got、node-fetch三个主流HTTP库的代理配置方式各不相同。本文三个库的代理写法一次性对比清楚。
axios配代理
const axios = require('axios');
// HTTP代理
const resp = await axios.get('https://ip.sb', {
proxy: {
host: '代理IP',
port: 端口,
auth: { username: '用户名', password: '密码' }
}
});
// SOCKS5代理(需安装socks-proxy-agent)
const { SocksProxyAgent } = require('socks-proxy-agent');
const agent = new SocksProxyAgent('socks5://代理IP:端口');
const resp = await axios.get('https://ip.sb', { httpAgent: agent });got配代理
const got = require('got');
const { HttpsProxyAgent } = require('hpagent');
const resp = await got('https://ip.sb', {
agent: {
https: new HttpsProxyAgent({ proxy: 'http://代理IP:端口' })
}
});node-fetch配代理
const fetch = require('node-fetch');
const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://代理IP:端口');
const resp = await fetch('https://ip.sb', { agent });天行IP(邀请码 blsj,月付6元起)静态节点在Node.js里配合axios/got做采集或API代理。
三个库的选择
| 库 | 代理易用性 | 性能 | 建议 |
|---|---|---|---|
| axios | 原生支持HTTP代理 | 中 | API调用首选 |
| got | 需hpagent插件 | 高(HTTP/2) | 高性能采集 |
| node-fetch | 需https-proxy-agent | 中 | 熟悉fetch API选它 |
常见问题
Node.js代理报”self signed certificate”?
在agent配置里加 rejectUnauthorized: false 跳过证书校验。仅测试用,正式环境不要关。
三个库哪个支持SOCKS5最好?
got配合socks-proxy-agent支持完整SOCKS5;axios也可以用但需要额外agent。node-fetch配合socks-proxy-agent同样可以。






