在 react (port 3001)專案呼叫 Laravel (port 8000) 專案 api 發生了 cors 問題,因為不是很了解 cors 是什麼,所以記錄一下 # 同源政策 是一種`瀏覽器`的安全機制,它會限制來自不同「來源(origin)」的網頁之間的互動。其目的是防止惡意網站從使用者瀏覽器竊取敏感資料。 ## 同源? 要如何判斷是同源呢要判斷3個部分,以下3個部分相同才會被視為同源 - `protocol` ex: http、https - `port` ex: 80、443 - `host` ex: localhost、google 例如: http://localhost | 網址 | 是否同源 | 原因 | | -------- | -------- | -------- | | https://localhost | N | protocol 不同 | | http://localhost:999 | N | port 不同 | | http://google.com | N | host 不同 | | http://localhost/api/users | Y | 只有 path 不同 | # 為什麼會導致 cors 問題 - 因為同源政策([same-origin policy](https://rbika.com/blog/understanding-cors))的緣故是由`瀏覽器`去判斷的,同源政策是在說當來源A請求來源B的時候,會去判斷 `protocol` 和 `port` 和 `host`,主要是在預防非授權的資源請求. # 什麼是CORS(Cross-Origin Resource Sharing)呢? - 是一種基於http header的機制,讓 sever 告訴瀏覽器什麼樣的 origin 是可以取得資源的. - 會去判斷 request 的 Origin header 和 response 的 Access-Control-Allow-Origin header ``` - [o] request 的 origin 是 localhost:8000 且 response 回傳的 Access-Control-Allow-Origin 是 localhost:8000 或 * - [x] request 的 origin 是 localhost:8000 但 response 回傳的 Access-Control-Allow-Origin 不是 localhost:8000 或 * ``` - 如果是非 GET、POST、HEAD 或包含非標準的header,在實際發出 request 之前瀏覽器會先發 pre-flight request 是用 options http method,server 回應必需要包含 `Access-Control-Allow-Origin` 和 `Access-Control-Allow-Methods` 且是包含 client 端請求的 origin 和 Http method. ## 簡單請求 符合以下條件就是簡單請求: 1. 是 GET /HEADE/POST 其中一個 HTTP method 2. header 只能有以下的 - Accept - Accept-Language - Content-Type - Range 3. Content-Type 是以下 - application/x-www-form-urlencoded - multipart/form-data - text/plain 4. 請求是使用 XMLHttpRequest 且 XMLHttpRequest.upload 沒有註冊任何事件監聽器 5. 請求中沒有 ReadableStream server 只要在回傳 header 中加上 ``` Access-Control-Allow-Origin: https://your.site.com ``` 就可以成功取得資源 ## Preflight Request - 如果非簡單請求,就會先發送一個 options 的request ``` OPTIONS /users/ Host: test.com Origin: https://test.com/ Access-Control-Request-Method: POST Access-Control-Request-Headers: Content-Type ``` server 回傳的 headers 需要包含以下都要符合才可以取得資源 1. Access-Control-Allow-Methods 2. Access-Control-Allow-Headers 3. Access-Control-Allow-Origin # 參考資源 - https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy - https://rbika.com/blog/understanding-cors - https://medium.com/starbugs/%E5%BC%84%E6%87%82%E5%90%8C%E6%BA%90%E6%94%BF%E7%AD%96-same-origin-policy-%E8%88%87%E8%B7%A8%E7%B6%B2%E5%9F%9F-cors-e2e5c1a53a19 - https://www.shubo.io/what-is-cors/ - https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS#what_requests_use_cors
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up