CORS
CORS(跨源资源共享)是浏览器安全机制,用 HTTP 头控制网页能否访问不同源的资源,防止跨站读取。
用途
放宽同源策略以支持合法跨源 API 调用,同时防止恶意站点读取跨源响应。
机制
浏览器对跨源请求加 Origin 头。简单请求直接发送;预检请求(OPTIONS)检查服务器允许的方法与头。服务器返 Access-Control-Allow-Origin 等头授权。无凭证请求需 Allow-Credentials。
用例
- 跨域 API 调用
- CDN 字体与图片
- 微服务前端聚合
- 第三方 SDK 集成
示例
- 输入
Origin: https://a.com → https://b.com输出b.com returns the ACAO header to authorizePreflight followed by the actual request
常见错误
- The browser blocks the response when the server returns no CORS headers
- Configure the Access-Control-Allow-* headers