You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular+Azure Functions场景下CORS OPTIONS请求缓存差异原因排查

Azure Functions与Angular应用的CORS OPTIONS预检请求缓存差异分析

我开发了一个对接Azure Functions后端的Angular应用,为提升性能打算缓存CORS OPTIONS预检请求。真实项目里多次尝试都没成功,但在简易的Angular+Azure Functions示例中却顺利实现了缓存。以下是两个OPTIONS请求的详情,需要明确两者缓存差异的原因:

未被缓存的请求

Request URL: https://foo.azurewebsites.net/api/GetFooHttpTrigger
Request Method: OPTIONS
Status Code: 200 OK

Remote Address: 20.50.2.47:443
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: GET,POST
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 86400
Content-Length: 0
Date: Wed, 21 Dec 2022 14:31:32 GMT

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: authorization,content-type,x-apptimezone,x-customheader-ui,x-customheader-debug
Access-Control-Request-Method: POST
Connection: keep-alive
Host: foo.portal.dev.rel150.cloud.techie
Origin: https://foo.portal.dev.rel150.cloud.techie
Referer: https://foo.portal.dev.rel150.cloud.techie/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.54

已被缓存的请求

Request URL: http://localhost:7071/api/todo
Request Method: OPTIONS
Status Code: 200 OK

Remote Address: 127.0.0.1:7071
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Headers: *
Access-Control-Allow-Methods: post, get, delete, patch
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 3600
Content-Length: 0
Date: Wed, 21 Dec 2022 15:17:33 GMT
Server: Kestrel

Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Access-Control-Request-Headers: content-type,customheader1
Access-Control-Request-Method: POST
Connection: keep-alive
Host: localhost:7071
Origin: http://localhost:4200
Referer: http://localhost:4200/
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

缓存差异的核心原因

  1. 跨域场景限制
    未被缓存的请求属于cross-site跨域场景(Origin是foo.portal.dev.rel150.cloud.techie,请求目标是foo.azurewebsites.net,属于完全不同的域名),而缓存成功的请求是same-site(同localhost下不同端口,浏览器视为同一站点)。浏览器对跨站点的预检请求缓存策略更严格,即使返回了Access-Control-Max-Age,也可能出于安全考量拒绝缓存;而同一站点的请求则会正常遵循缓存时长设置。

  2. Azure生产环境的中间件影响
    真实项目的Azure Functions部署在官方托管环境,可能经过Azure App Service网关、CDN等中间件,这些组件可能会修改或忽略Access-Control-Max-Age响应头,甚至添加隐性的禁止缓存字段,导致浏览器无法识别缓存指令。而本地示例用的是Kestrel服务器,没有额外中间件,响应头能完整传递给浏览器。

  3. 请求头复杂度的间接影响
    未被缓存的请求携带的自定义请求头更多(5个),虽然后端返回Access-Control-Allow-Headers: *理论上支持所有头,但部分浏览器在处理跨域且请求头较多的预检请求时,会触发更严格的校验逻辑,间接导致缓存失效。

内容的提问来源于stack exchange,提问作者Yoss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 23:01:34