Firefox 102.0报CORS Method Not Found,但预检响应含PATCH方法
Firefox 102 PATCH请求CORS报错排查与解决
问题详情
使用Firefox 102.0发起PATCH请求时,浏览器提示「无法在access-control-allow-methods中找到PATCH方法」,但预检响应头明明包含该方法:
server: uvicorn access-control-allow-origin: * access-control-allow-methods: DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT access-control-max-age: 600 access-control-allow-headers: Accept, Accept-Language, Content-Language, Content-Type content-length: 2 content-type: text/plain; charset=utf-8
请求头信息:
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Access-Control-Request-Method: PATCH Access-Control-Request-Headers: content-type Referer: http://localhost:8080/ Origin: http://localhost:8080 Connection: keep-alive Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site
Firefox报错为CORS Method Not Found,但POST、DELETE方法可正常工作,且该请求在Chrome中无问题。FastAPI的CORS中间件配置如下:
middleware=[Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"])],
另外,该PATCH请求未携带任何内容/数据。
排查与解决方法
1. 替换通配符为明确的方法列表
虽然allow_methods=["*"]理论上允许所有HTTP方法,但Firefox 102这类旧版本浏览器在处理预检请求时,可能无法正确解析通配符,而是要求明确列出允许的方法。修改FastAPI配置:
middleware=[ Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] ), ],
手动指定方法后,能避免浏览器对通配符的解析异常。
2. 给PATCH请求添加空请求体
Firefox对无请求体的PATCH请求可能有特殊的CORS校验逻辑。尝试在请求中添加一个空的请求体(比如{}),并设置正确的Content-Type(如application/json)。例如前端代码中:
fetch('/your-endpoint', { method: 'PATCH', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({}) // 添加空对象作为请求体 })
3. 清除Firefox缓存或禁用缓存
浏览器可能缓存了之前错误的预检响应,即使现在响应正确,仍会使用旧缓存验证。解决方式:
- 打开Firefox开发者工具(F12),切换到「网络」面板,勾选左上角的「禁用缓存」,重新发起请求
- 手动清除浏览器缓存(Ctrl+Shift+Del),选择「缓存」项清除
4. 调整CORSMiddleware的优先级
如果FastAPI中还有其他中间件,可能会修改CORS响应头。确保CORSMiddleware放在中间件列表的最前面,让它优先处理请求和响应:
middleware=[ # 把CORSMiddleware放在最顶部 Middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] ), # 其他中间件放在后面 # Middleware(OtherMiddleware), ],
内容的提问来源于stack exchange,提问作者buco
相关产品推荐
相关产品推荐

