如何在ReactJS中無視cors地使用fetch載入資源

Eluspac
Dec 15, 2020

--

最近因為要處理一個 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,可參考原文:

原文: https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Eluspac
Eluspac

No responses yet

Write a response