快轉到主要內容

Cross-Origin Resource Sharing (CORS) 跨來源資源共用錯誤解決方法

932 字2 分鐘00
作者Y Cheung
目錄

最近Y cheung 遇到了兩個典型 CORS error問題,XMLHttpRequest 和 Fetch 請求了跨來源資源被瀏覽器阻擋,記錄一下解決方法。

什麼是Cross-Origin Resource Sharing (CORS) 跨來源資源共用?#

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.

簡單來說,就是當你的站點對別的站點發起資源請求的時候,這個http請求就叫做跨來源HTTP請求(cross-origin HTTP request)。網域(domain)、通訊協定(protocol)或通訊埠(port)不同都視為別的站點。

基於安全考量,你的跨來源資源請求會受到限制。XMLHttpRequest 請求和 Fetch 請求默認遵守同源政策(same-origin policy),也就是Y cheung最近遇到的問題所在。

網頁上一般會遇到CORS錯誤的情況:#

  • XMLHttpRequest 請求
  • Fetch 請求
  • 加載 Web Fonts
  • 加載 WebGL textures
  • 在canvas中使用drawImage() 圖片或視頻幀
  • 使用了圖片的 CSS shape

了解更多有關於CORS的信息可以參看《MDN Web Docs:Cross-Origin Resource Sharing (CORS)》

解決AWS S3上的svg圖片因CORS Error 無法顯示問題#

網站圖片包括svg圖片都放在AWS S3上,就SVG圖片無法顯示,檢查console找到以下錯誤信息:

chrome display cors error
Access to XMLHttpRequest at ‘https://s3.ap-southeast-1.amazonaws.com/public/icons/icon_select_map.svg' from ‘https://example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is prevent on the request resource.

此CORS policy error 觸發了XMLHttpRequest同源政策限制,解決辦法就是在AWS S3上正確設置CORS,參看《AWS S3使用者指南:設定跨來源資源分享 (CORS)》。

解決React fetch 自定义header 请求 CORS Error問題#

前端 React 用 fetch 發起請求:

 1const headers = {
 2  'Content-Type': 'application/json',
 3  Origin: 'http://google.com',
 4  Accept: '*/*',
 5  'Sec-Fetch-Dest': 'empty',
 6  'Sec-Fetch-Mode': 'cors',
 7  'Sec-Fetch-Site': 'same-origin',
 8  mode: 'cors',
 9};
10
11export const getSummary = params => {
12  const url = new URL(`${API_URL}`);
13  const bodyParam = fiterout(JSON.stringify(params));
14  return fetch(url, {
15    method: 'POST',
16    headers,
17    body: bodyParam,
18  }).then(r => r.json());
19};

由于自定義的請求頭部 header 觸發了 fetch 同源政策限制(Content-Type、Accept等):

chrome display cors error
Access to fetch at ‘http://localhost’ from origin ‘http://localhost:3006’ has been blocked by CORS policy: Request header field mode is not allowed by Access-Control-Allow-Headers in preflight response.

Y Cheung 的解決辦法是在接收請求的endpoint上加上相應的header,例如:

 1<?php
 2if ( isset( $_SERVER['HTTP_ORIGIN'] ) ) {
 3	header( "Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}" );
 4	header( 'Access-Control-Allow-Credentials: true' );
 5}
 6if ( $_SERVER['REQUEST_METHOD'] == 'OPTIONS' ) {
 7	if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] ) ) {
 8		header( "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS" );
 9	}
10	if ( isset( $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'] ) ) {
11		header( "Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}" );
12	}
13}
分享

相關文章

IPTABLES 封鎖 IP 黑名单

作者 Y Cheung268 字1 分鐘00

在服務器上增加 iptables chain 新建 bash 文件 banip.sh 在這個文件中,首先清空 black_ip_list 中的規則, 然後從 …

使用Cloudflare加速和保護你的Wordpress網站

作者 Y Cheung2013 字5 分鐘00

Cloudflare 是提供基於反向代理的內容傳遞網路及分布式域名解析的服務,也就是我們俗稱的CDN加速。它不僅可以緩存網站內容,加速網站提升用戶體驗,還能進行簡單的防火牆設置,讓 …

SEO 結構化資料指南

作者 Y Cheung801 字2 分鐘00

結構化資料是一種標準化格式,它提供網頁相關資訊並將網頁內容分類,有助於優化搜索引擎SEO。 ⚠ 即使網頁已正確加上標記,Google 也不能保證結構化資料一定會出現在搜尋結果中。

Web Accessibility 無障礙網頁

作者 Y Cheung349 字1 分鐘00

Web Accessibility 就是我們通常所說的無障礙網站,這裡的「障礙」包括了聽覺障礙、認知能力障礙、神經損傷、身體障礙、語言障礙和視覺障礙,這也是基本人權的一個方面。

Chrome 實驗性功能 CSS Overview

作者 Y Cheung325 字1 分鐘00

Chrome上了新的實驗性功能 CSS Overview,感覺對做網站前端十分有用,可以快速查閱網站上所使用的顏色、字體、未使用的css申明、定義的媒體查詢。

↑