Ⅰ. はじめに
タイトルの通り「node-fetchでproxyを設定する方法」です。
Ⅱ. やり方
1. 必要なパッケージをインストールする
npm install node-fetch npm install http-proxy-agent npm install https-proxy-agent
2. サンプルプログラムを書く
index.js
const fetch = require('node-fetch'); // const HttpProxyAgent = require('http-proxy-agent'); const HttpsProxyAgent = require('https-proxy-agent'); (async () => { // process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0 const proxyAgent = new HttpsProxyAgent('http://10.0.0.2:3128') // const proxyAgent = new HttpsProxyAgent('http://username:password@10.0.0.2:3128') const response = await fetch('https://api.ipify.org/?format=json', { agent: proxyAgent }) const json = await response.json() console.log(json) })()
実行結果
$ node index.js { ip: '107.x.x.x' }