概述预检(OPTIONS)用于验证跨源请求方法与头部。`Access-Control-Max-Age` 决定预检结果的缓存时长,可降低频繁预检开销,但不宜设置过长以免放大误配风险。示例:Nginx/Node 配置location /api/ { if ($request_method = OPTIONS) { add_header Access-Control-Allow-Origin "https://app.example"; add_header Access-Control-Allow-Methods "GET, POST, PUT"; add_header Access-Control-Allow-Headers "Content-Type, Authorization"; add_header Access-Control-Max-Age 600; return 204; } add_header Access-Control-Allow-Origin "https://app.example"; proxy_pass http://backend; } // Express 中处理预检 app.options('/api/*', (req, res) => { res.set({ 'Access-Control-Allow-Origin': 'https://app.example', 'Access-Control-Allow-Methods': 'GET,POST,PUT', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Max-Age': '600' }) res.sendStatus(204) }) 工程建议精准白名单:仅允许必要来源/方法/头;动态场景以令牌或签名鉴权为主。缓存时长:根据风险与变更频率设置中等 TTL(如 10–30 分钟);重大变更前缩短 TTL。监控与告警:记录跨源失败与预检命中;避免误配置长期生效。参考与验证MDN CORS 预检说明:https://developer.mozilla.org/docs/Web/HTTP/CORS#preflighted_requestsWHATWG Fetch 规范:https://fetch.spec.whatwg.org/web.dev CORS 与安全实践:https://web.dev/articles/cors

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部