Node.js Axios 中的 HTTP 和 SOCKS 代理
在 Axios 的 Node HTTP 适配器中配置 HTTP 代理;若选中的 IP 是 SOCKS 端点,则使用 SOCKS agent。
Axios 的 Node HTTP 适配器接受包含主机和数值端口的 HTTP 代理对象:
import axios from 'axios';
const response = await axios.get('https://example.com/', {
adapter: 'http',
proxy: {
protocol: 'http',
host: '203.0.113.10',
port: 8080,
},
timeout: 15000,
});
console.log(response.status);
将文档示例端点替换为你的服务或 HTTP 代理列表中的 HTTP 条目。这些示例使用 Node;浏览器中的 Axios 无法通过这些选项选择浏览器的网络代理。host 字段只填地址,不包含 URL 协议方案。
代理对象的 protocol 描述的是其监听端。在 Axios 1.21.0 中,Node HTTP 适配器为 HTTPS 目标使用 CONNECT,再通过隧道与源站协商 TLS。旧版本曾采用不同的代理路径,因此已安装版本很重要。
SOCKS URL 需要 SOCKS agent
HTTP 代理对象不能选择 SOCKS。应改用兼容的 agent:
npm install [email protected] [email protected]
import axios from 'axios';
import { SocksProxyAgent } from 'socks-proxy-agent';
const agent = new SocksProxyAgent('socks5h://203.0.113.10:1080');
try {
const response = await axios.get('https://example.com/', {
adapter: 'http',
httpAgent: agent,
httpsAgent: agent,
proxy: false,
timeout: 15000,
});
console.log(response.status);
} finally {
agent.destroy();
}
proxy: false 会禁用 Axios 对 SOCKS agent 所提供路由的 HTTP 代理处理。同时为 HTTP 和 HTTPS 目标提供该 agent,可覆盖两种协议方案。这里的 socks5h 会将目标 DNS 解析交给 SOCKS 一侧;选用的服务器必须支持该协议。
解读故障
网站返回不成功的状态时,Axios 错误可能包含响应。若没有响应,应检查错误码和连接细节。缺少模块、不支持的协议或不兼容的 Node 版本,都可能在请求抵达端点前导致失败。
对于需要认证的 HTTP 代理,使用代理对象的 auth 字段,并填入运营方提供的凭据。目标服务器的认证设置服务的是另一方。