Skip to content

CORS

学习 Cross-原点 Resource Sharing (CORS) — 为什么它 exists and 如何 配置它.

你将学到

  • 什么相同-原点 policy 是 and 为什么浏览器 enforce 它
  • 什么 CORS 是 and 如何它 relaxes 相同-原点 policy safely
  • 如何 preflight 请求 (OPTIONS) 工作 for 非-简单请求
  • 配置 CORS 请求头 on 服务器: Access-Control-允许-原点 and 更多

概念讲解

CORS

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how a web page can request resources from a *different origin* than its own. An origin is the combination of scheme, host, and port — https://api.example.com and https://app.example.com are different origins. CORS is the source of the infamous "blocked by CORS" error, but understanding it turns that error from a mystery into a configuration task.

The Same-Origin Policy

By default, browsers enforce the same-origin policy: JavaScript on a page from origin A can only make 获取 requests to origin A. A page at https://app.example.com cannot fetch https://api.example.com unless the API explicitly allows it. This policy prevents malicious sites from reading data from other sites where you might be logged in. It is a fundamental security boundary.

How CORS Works

CORS lets the server *opt in* to cross-origin requests by sending specific HTTP headers. The browser checks these headers and allows or blocks the response:

  • Access-Control-允许-原点: https://app.example.com — allows this specific origin.
  • **Access-Control-允许-原点: *** — allows any origin (use only for public APIs, never with credentials).
  • Access-Control-允许-方法: GET, POST, PUT, DELETE — which methods are allowed.
  • Access-Control-允许-请求头: 内容-类型, 授权 — which request headers are allowed.

The browser does the checking automatically — you do not handle CORS in client-side code. The server must send the right headers.

Preflight Requests

For "简单" requests (GET/POST with basic headers), the browser sends the request directly. For "non-simple" requests — custom headers like 授权, methods like PUT or DELETE, or 内容-类型: application/JSON — the browser first sends a preflight OPTIONS request to check if the actual request is allowed. Only if the preflight passes does the browser send the real request. This two-step process is why you sometimes see an OPTIONS request in DevTools before your actual request.

Credentials and CORS

If your cross-origin request includes cookies (credentials), Access-Control-允许-原点: * is not allowed — you must specify the exact origin, and set Access-Control-允许-Credentials: 真. This is a common stumbling block: a wildcard origin with credentials fails, even if everything else is correct.

CORS is a Browser Feature

CORS is enforced by the browser, not the server. The server sends headers; the browser decides whether to let your JavaScript see the response. Server-to-server requests (e.g., your backend calling another API) do not have CORS restrictions — there is no browser involved. This is why CORS errors only appear in browser-based code.

示例代码

              // Server-side CORS configuration (Node.js / Express)
const express = require("express");
const app = express();

// Manual CORS headers for a specific origin
app.use((req, res, next) => {
  const allowedOrigin = "https://app.example.com";
  res.setHeader("Access-Control-Allow-Origin", allowedOrigin);
  res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  res.setHeader("Access-Control-Allow-Credentials", "true");
  res.setHeader("Access-Control-Max-Age", "86400"); // cache preflight

  // Handle the preflight OPTIONS request
  if (req.method === "OPTIONS") {
    return res.sendStatus(204);
  }
  next();
});

// Client-side: a cross-origin fetch with credentials
async function fetchProfile() {
  const response = await fetch("https://api.example.com/profile", {
    credentials: "include",  // send cookies cross-origin
    headers: { "Authorization": "Bearer " + token }
  });
  return response.json();
}
            

服务器设置 CORS 请求头 for 特定原点 (不 wildcard, 因为 credentials 是 involved). 它 handles OPTIONS preflight 请求通过 returning 204. 客户端 uses credentials: '包含' 到发送 Cookie cross-原点. preflight 是 cached for 86400 seconds 到 reduce overhead.

动手试一试

  • JSON Formatter

    CORS 错误经常 involve JSON API 响应 — 格式它们到 inspect 错误.

  • URL Encoder

    Cross-原点 URLs 有时需要 encoding — 检查你的请求 URLs.

常见错误

错误写法

Using Access-Control-允许-原点: * 使用 credentials: '包含' in 获取.

正确做法

wildcard 原点是 不允许当 credentials 是 involved. 你必须 specify 精确原点 (e.g., https://app.example.com) and 设置 Access-Control-允许-Credentials: 真 on 服务器.

错误写法

Thinking CORS 是服务器-边 restriction 那个块 请求从 arriving.

正确做法

CORS 是 enforced 通过浏览器. 服务器接收 and 处理请求通常 — 它是 浏览器那个块 你的 JavaScript 从读取响应如果 CORS 请求头是 missing or 错误. fix 是总是 on 服务器 (发送正确请求头), 不客户端.

相关指南

练习 CORS

3 个练习

练习 CORS

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误