最近因為要處理一個 youtube thumbnail 問題,由於youtube的thumbnail中的 maxresdefault /hqdefault 可能並不存在,所以需要進行fallback image的處理,所以需要使用fetch先獲取thumbnail的回傳狀態(例如是否404)。
但期間遇到cors的阻攔,導致無法解決。
經E同事在 stackoverflow 的搜查後發現可以使用 url proxy的形式去進行回傳,
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://example.com"; //需要回傳的網址fetch(proxyurl + url)
合併結果:
https://cors-anywhere.herokuapp.com/https://example.com
代碼如下:
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://example.com"; //需要回傳的網址const response = await fetch(proxyurl + url);
console.log(response.status); //回傳代碼或fetch(proxyurl + url)
.then(response => response.text()) //可在此獲取回傳代碼
.then(contents => console.log(contents))
.catch(() => console.log("仍無法獲取"))
至於如何設定proxy server,可參考原文: