Agentic Research

CORS (Cross-Origin Resource Sharing)

Also: 跨來源 · 跨域 · CORS 錯誤 · Access-Control-Allow-Origin · 瀏覽器攔擋

A browser security gate: when page JavaScript asks a server of a different origin for data, the server must explicitly allow it, or the browser blocks the response.

When you will meet it

This is the classic reason "my script works but fails once it is in a web page". The same API call runs fine from curl or Python, but moving it to browser front-end gets blocked by CORS. Without this you keep thinking your code is wrong.

An analogy

Like a building's access control: it is not the server refusing your data, it is the browser acting as a guard with a rule that "page A may not freely request from site B" unless B has registered "I allow A". The guard is the browser, not the server.

Minimal example

瀏覽器 console 跳出:
  Access to fetch at 'https://api.model.com/v1/chat' from origin
  'https://myapp.com' has been blocked by CORS policy:
  No 'Access-Control-Allow-Origin' header is present ...

注意:這行錯誤是「瀏覽器」印的,不是伺服器拒絕你。
伺服器其實有回資料,只是瀏覽器認為未獲授權,把回應扣下來、不交給你的腳本。

Two points. First, CORS only happens in browsers: calls between curl, Python and back-end servers have no such restriction, because they are not browsers. Second, the correct fix is for the server to return an Access-Control-Allow-Origin header — but you cannot change a model API's server, so the real fix is to move the call to your own back-end, which queries the API and hands the result to the front-end. You cannot bypass it by adding some header on the client.

What people get wrong

  • Trying to "add a header" on the front-end to switch CORS off. CORS is enforced by the browser and the client cannot disable it; whether cross-origin is allowed is decided by the server's response headers, not by you.
  • Assuming "if the back-end works, the front-end must too". The opposite is true: there is no CORS between servers, only in browsers. Copying the same code verbatim to the front-end is the most common way a CORS error is born.

Related terms

Next