Cloudflare Worker 可以方便的中轉 HTTP 請求,下面示例是我之前用過的,算是密碼保護的中轉特定請求。其中的 X_Custom_PSK 算是密碼,在 Settings > Variables 設置,這樣就只有我的程序可以請求。
addEventListener("fetch", event => { const psk = event.request.headers.get("X_Custom_PSK"); if (psk === X_Custom_PSK) { event.respondWith(handleRequest(event.request)); }else{ const failed_response = new Response('Sorry, you have supplied an invalid key.', { status: 403, }); event.respondWith(failed_response); } }) async function handleRequest(request) { const resp = await fetch('https://domain.ltd/checkpoint/list', { method: 'POST', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.3 Safari/537.36', 'Accept': '*/*', 'Accept-Language': 'zh-CN;q=0.8,zh;q=0.6,en-US;q=0.4,en;q=0.2', 'Origin': 'https://domain.ltd', 'DNT': '1', 'Connection': 'keep-alive', 'Referer': 'https://domain.ltd/', 'Sec-Fetch-Dest': 'empty', 'Sec-Fetch-Mode': 'cors', 'Sec-Fetch-Site': 'cross-site' }, body: new URLSearchParams({ 'page': '1', 'pageSize': '10', 'latitude': '22.5', 'longitude': '114.0', 'queryType': '0' }) }); return resp; }
下面這個則是用一個 worker 代理多個網站。
addEventListener("fetch", event => { let url=new URL(event.request.url); if (event.request.url.indexOf('shaman')>-1){ url.hostname="ft.shaman.eu.org"; }else{ url.hostname="www.rfi.fr"; } let request=new Request(url,event.request); event.respondWith(fetch(request)); });