跳转到内容

CORS

cors 中间件自动处理 CORS 预检请求(OPTIONS)并在响应中附加跨域头。

import { cors } from "@ventostack/core";
// 允许单个源
app.use(cors({ origin: "https://example.com" }));
app.use(cors({
origin: ["https://a.com", "https://b.com"],
}));
app.use(cors({
origin: (origin) => origin.endsWith(".example.com"),
}));
app.use(cors({
origin: "https://example.com",
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
exposedHeaders: ["X-Total-Count"],
credentials: true,
maxAge: 86400, // 预检缓存 24 小时
}));
属性类型默认值说明
originstring | string[] | (origin) => boolean允许的源(不设置则拒绝)
methodsstring[]["GET","HEAD","PUT","PATCH","POST","DELETE"]允许的 HTTP 方法
allowedHeadersstring[]反射请求头允许的请求头
exposedHeadersstring[]暴露给客户端的响应头
credentialsbooleanfalse是否允许携带凭证
maxAgenumber预检请求缓存时间(秒)
  • credentials: trueorigin: "*" 不可同时使用,会抛出错误
  • Origin 请求头时中间件不处理 CORS(直接放行)
  • 未匹配的源在预检请求时返回 403