> For the complete documentation index, see [llms.txt](https://jack1in.gitbook.io/font-end/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jack1in.gitbook.io/font-end/1.-web/1.6-cors.md).

# 1.6 CORS

瀏覽器因為安全性的考量，有一個東西叫做**同源政策，Same-origin policy**。

意思就是說如果你現在這個網站的跟你要呼叫的 API 的網站「不同源」的時候，瀏覽器一樣會幫你發 Request，但是會把 **Response 擋下來**，不讓你的 JavaScript 拿到並且傳回錯誤。

什麼是不同源呢？其實你想簡單一點，只要是 Domain 不一樣就是不同源，或者是一個用`http`一個用`https`也是不同源，端口號不一樣也是不同源。

所以如果你是接別人 API 的話，大多數情形都是不同源的。

再次強調一點，「你的 Request 還是有發出去的」，而且瀏覽器也「確實有收到 Response」，重點是「瀏覽器因為同源政策，不把結果傳回給你的 JavaScript」。如果沒有瀏覽器的話其實就沒有這些問題，你愛發給誰就發給誰，不管怎樣都拿得到 Response。

**CORS，全名為 Cross-Origin Resource Sharing，跨來源資源共享。**

這套規範跟你說，如果你想開啟跨來源 HTTP 請求的話，Server 必須在 Response 的 Header 裡面加上`Access-Control-Allow-Origin`。

```
Content-Type: application/json
Content-Length: 71
Connection: keep-alive
Server: nginx
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, must-revalidate, private
Expires: 0
Pragma: no-cache
Twitch-Trace-Id: e316ddcf2fa38a659fa95af9012c9358
X-Ctxlog-Logid: 1-5920052c-446a91950e3abed21a360bd5
Timing-Allow-Origin: https://www.twitch.tv
```

重點是這一行：`Access-Control-Allow-Origin: *`，星號就代表萬用字元，意思是任何一個 Origin 都接受。所以當瀏覽器接收到這個 Response 之後，比對目前的 Origin 符合`*`這個規則，檢驗通過，允許我們接受跨來源請求的回應。

node.js 請求代理\
客戶端發起請求到nodejs server，nodejs收到後請求第三方server取得數據，返回客戶端。<br>

```
client ajax --> nodejs recived --> nodejs send request --> respone to client
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://jack1in.gitbook.io/font-end/1.-web/1.6-cors.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
