大网数据广告活动
Web 标准与前端开发

Cross-Origin Resource Sharing (CORS) configuration

· 52CE 我爱测

Cross-Origin Resource Sharing (CORS) is handled using `Access-Control-Allow-Origin` and related headers. `Access-Control-Allow-Origin` defines the non-same origins that are allowed to make requests to pages on your domain (i.e., via `XMLHttpRequest` or `fetch()`).

Cross-Origin Resource Sharing (CORS) is handled using Access-Control-Allow-Origin and related headers. Access-Control-Allow-Origin defines the non-same origins that are allowed to make requests to pages on your domain (i.e., via XMLHttpRequest or fetch()).

Problem

By default, same-origin policy blocks cross-origin HTTP requests initiated by scripts. There are several use cases that require cross-origin script access; for example, Content Delivery Networks (CDNs) that provide hosting for JavaScript/CSS libraries and public API endpoints. However, cross-origin access presents a major security risk and must be carefully controlled.

Solution

Use Access-Control-Allow-Origin to define the non-same origins that are allowed to make requests to pages on your domain.

If present, Access-Control-Allow-Origin should specify the minimum possible number of origins and resources for your site to function. For example, if your server provides both a website and an API intended for remote XMLHttpRequest access, only the API resources should return the Access-Control-Allow-Origin header.

Failure to set Access-Control-Allow-Origin appropriately will allow unauthorized origins to read the contents of any page on your site. This can be especially dangerous if those sites are able to send credentials, potentially exposing your site to CSRF attacks.

If credentialed access is required from specific origins, ensure Access-Control-Allow-Origin is set only to those origins, rather than reflecting the Origin header. If public non-credentialed access is required, set Access-Control-Allow-Origin to * and omit the Access-Control-Allow-Credentials header. Otherwise, omit both headers.

Examples

Allow any site to read the contents of a JavaScript library:

Access-Control-Allow-Origin: *

[!NOTE] This setting is required for Subresource integrity to work.

Allow https://random-dashboard.example.org to read the returned results of an API:

Access-Control-Allow-Origin: https://random-dashboard.example.org

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。