What is CORS?

跨來源資源共享(CORS,Cross-Origin Resource Sharing是一種安全機制,用於限制網頁從與服務其網頁的域名不同的域名發起請求。這樣做的目的是防止惡意網站訪問其他網站的敏感數據。

When a web page makes a request to a different domain than the one that served the web page, this is called a cross-origin request. Cross-origin requests are subject to a security mechanism called CORS (Cross-Origin Resource Sharing).

Cross-Origin Resource Sharing (CORS) is a security mechanism that restricts web pages from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from accessing sensitive data from other websites.

The Process of Making Requests to Different Domains

當網頁向不同域名發起請求時,瀏覽器會向服務器發送一個預檢請求(preflight request),以檢查服務器是否允許跨來源請求。如果服務器允許請求,它會發送帶有適當 CORS 標頭的響應。然後,網頁可以發起實際請求並接收響應。

When a web page needs to fetch information from a different website, it sends a request to that website's server. To ensure security, the web page's browser first sends a "preflight request" to check if the other website allows this cross-origin request. If the other website permits the request, it sends a response with the necessary CORS (Cross-Origin Resource Sharing) headers. The web page can then proceed with the actual request and receive the response.

CORS 請求的步驟如下:

  1. 網頁向不同域名發起請求。
  2. 瀏覽器向服務器發送預檢請求,以檢查服務器是否允許跨來源請求。
  3. 服務器發送帶有適當 CORS 標頭的響應。
  4. 網頁可以發起實際請求並接收響應。

Steps Involved in a CORS Request:

  1. The web page initiates a request to a different domain.
  2. The browser sends a preflight request to the other website's server to verify if it allows cross-origin requests.
  3. The server responds with appropriate CORS headers indicating whether the request is permitted.
  4. If allowed, the web page sends the actual request and receives the response from the server.