当前位置: 首页 > Skill >

CORS

CORS

CORS

正确配置跨域资源共享,避免安全隐患与调试困扰。

1.0.0 2026.11.20 612
获取Skill文件查看使用说明
类 别:PHP 跨域请求解决方法 作 者:叶舟 许可证: 更新时间:2026.11.20
本文目录展开

Preflight Triggers

  • Any header except: Accept, Accept-Language, Content-Language, Content-Type (with restrictions)
  • Content-Type other than: application/x-www-form-urlencoded, multipart/form-data, text/plain
  • Methods: PUT, DELETE, PATCH, or any custom method
  • ReadableStream in request body
  • Event listeners on XMLHttpRequest.upload
  • One trigger = preflight; simple requests skip OPTIONS entirely

Credentials Mode

  • Access-Control-Allow-Origin: * incompatible with credentials—must specify exact origin
  • Access-Control-Allow-Credentials: true required for cookies/auth headers
  • Fetch: credentials: 'include'; XHR: withCredentials = true
  • Without credentials mode, cookies not sent even to same origin for cross-origin requests

Wildcard Limitations

  • * doesn't match subdomains—*.example.com is invalid, not a pattern
  • Can't use * with credentials—specify origin dynamically from request
  • Access-Control-Allow-Headers: * works in most browsers but not all—list explicitly for compatibility
  • Access-Control-Expose-Headers: * same issue—list headers you need to expose

Origin Validation

  • Check Origin header against allowlist—don't reflect blindly (security risk)
  • Regex matching pitfall: example.com matches evilexample.com—anchor the pattern
  • null origin: sandboxed iframes, file:// URLs—usually reject, never allow as trusted
  • Missing Origin header: same-origin or non-browser client—handle explicitly

Vary Header (Critical)

  • Always include Vary: Origin when response depends on origin—even if you allow only one
  • Without Vary: CDN/proxy caches response for one origin, serves to others—breaks CORS
  • Add Vary: Access-Control-Request-Headers, Access-Control-Request-Method for preflight caching correctness

Exposed Headers

  • By default, JS can only read: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma
  • Custom headers invisible to JS unless listed in Access-Control-Expose-Headers
  • X-Request-ID, X-RateLimit-*, etc. need explicit exposure—common oversight

Preflight Caching

  • Access-Control-Max-Age: 86400 caches preflight for 24h—reduces OPTIONS traffic significantly
  • Chrome caps at 2 hours; Firefox at 24 hours—values above are silently reduced
  • Cached per origin + URL + request characteristics—not globally
  • Set to 0 or omit during development—caching hides config changes

Debugging

  • CORS error in browser = request reached server and came back—check server logs
  • Preflight failure: server must return 2xx with CORS headers on OPTIONS—404/500 = failure
  • Opaque response in fetch: mode: 'no-cors' succeeds but response is empty—usually not what you want
  • Network tab shows CORS errors; Console shows which header is missing

Common Server Mistakes

  • Only setting CORS headers on main handler, not OPTIONS—preflight fails
  • Setting headers after error response—CORS headers missing on 4xx/5xx breaks error handling
  • Proxy stripping headers—verify headers reach client, not just that server sets them
  • Access-Control-Allow-Origin: "*", "https://example.com"—must be single value, not list

Security

  • Don't reflect Origin header blindly—validate against allowlist first
  • Private Network Access: Chrome requires Access-Control-Allow-Private-Network: true for localhost access from public web
  • CORS doesn't prevent request from being sent—just blocks response reading; server still processes it
  • Sensitive endpoints: don't rely on CORS alone; use authentication + CSRF tokens

相关文章

更多
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
解决PHP处理Ajax请求时的跨域(CORS)问题

在 PHP 中解决 Ajax 跨域问题,核心是在响应头中设置 Access-Control-Allow-Origin 。最简单的方法是直接在脚本顶部输出该 Header ,允许特定域名或通配符访问。

2025.05.06 974
PHP后端怎么设置Access-Control-Allow-Origin解决跨域问题

在 PHP 后端解决跨域问题,最直接的方法是在脚本输出任何内容之前,通过 header() 函数设置响应头。关键步骤是调用 header('Access-Control-Allow-Origin: *'); (或指定具体域名),并确保该逻辑在所有业务逻辑执行前生效。

2025.02.21 911
原生PHP与Laravel框架中CORS跨域配置的差异与实现

原生 PHP 通过设置 HTTP 响应头解决跨域, Laravel 框架需在配置文件中定义 CORS 规则并加载中间件。

2026.03.20 824
PHP怎么处理携带Cookie或自定义Header的复杂跨域请求

在 PHP 中处理携带 Cookie 或自定义 Header 的复杂跨域请求,核心是正确配置响应头并配合前端设置。后端需返回 Access-Control-Allow-Origin 、 Access-Control-Allow-Credentials 等关键头部,且源不能为通配符 * ;前端则需在 XHR 或 Fetc

2026.03.17 794
跨域情况下JS怎么安全传值给PHP接口

跨域场景下, JS 向 PHP 接口传值最安全且通用的做法是: 使用 POST 请求发送 JSON 数据 ,并在 PHP 端通过 php://input 读取原始流解析为数组。避免使用 URL 拼接参数(易泄露、长度受限)或 GET 请求(缓存风险)。同时需配合 CORS 头配置与 CSRF Token 校验保障安全性

2026.08.21 382
Skill 文件
  • SKILL.md
    • Preflight Triggers
    • Credentials Mode
    • Wildcard Limitations
    • Origin Validation
    • Vary Header (Critical)
    • Exposed Headers
    • Preflight Caching
    • Debugging
    • Common Server Mistakes
    • Security
  • 项目或源文件

相关 Skill

更多
CORS Tester CORS Tester 测试并调试实时URL的CORS(跨域资源共享)配置。在检查服务器是否返回正确的CORS头、调试CORS错误时使用。
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...