JavaScript/Node.js API代理示例

流程:提取 API → 解析 JSON → 处理错误 → 使用返回代理访问目标站。

[!NOTE]提示

请将 apiUrl 替换为您自己的 API 提取链接。

原生 https + https-proxy-agent

const https = require('https');
const { request: httpsRequest } = https;
const HttpsProxyAgent = require('https-proxy-agent');

const apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';

function fetchJson(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      let data = '';
      res.on('data', (chunk) => (data += chunk));
      res.on('end', () => {
        if (res.statusCode !== 200) {
          return reject(new Error(`API错误 ${res.statusCode}`));
        }
        try {
          resolve(JSON.parse(data));
        } catch (e) {
          reject(e);
        }
      });
    }).on('error', reject);
  });
}

async function main() {
  const arr = await fetchJson(apiUrl);
  if (!Array.isArray(arr) || arr.length === 0) throw new Error('API 返回为空');
  const { ip, port } = arr[0];
  const agent = new HttpsProxyAgent(`http://${ip}:${port}`);

  const req = httpsRequest('https://httpbin.org/ip', { agent }, (res) => {
    let s = '';
    res.on('data', (c) => (s += c));
    res.on('end', () => console.log(s));
  });
  req.on('error', console.error);
  req.end();
}

main().catch((e) => {
  console.error(e.message);
  process.exit(1);
});

axios

const axios = require('axios');

const apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';

async function main() {
  const apiResp = await axios.get(apiUrl, { timeout: 10000 });
  const arr = apiResp.data;
  if (!Array.isArray(arr) || arr.length === 0) throw new Error('API 返回为空');
  const { ip, port } = arr[0];

  const r = await axios.get('https://httpbin.org/ip', {
    timeout: 10000,
    proxy: { host: ip, port: Number(port) },
    // 若需要用户名密码:proxy: { host: ip, port: Number(port), auth: { username, password } }
  });
  console.log(r.data);
}

main().catch((e) => {
  console.error(e.message);
  process.exit(1);
});

superagent

const request = require('superagent');
require('superagent-proxy')(request);

const apiUrl = 'http://ip.16yun.cn:817/myip/pl/<ORDER_ID>/?s=<ORDER_SIGN>&u=<USER>&format=json';

async function main() {
  const apiResp = await request.get(apiUrl).timeout({ response: 10000 });
  const arr = JSON.parse(apiResp.text);
  if (!Array.isArray(arr) || arr.length === 0) throw new Error('API 返回为空');
  const { ip, port } = arr[0];

  const res = await request
    .get('https://httpbin.org/ip')
    .proxy(`http://${ip}:${port}`)
    .timeout({ response: 10000 });
  console.log(res.text);
}

main().catch((e) => {
  console.error(e.message);
  process.exit(1);
});