PATCH请求与CORS跨域异常问题排查及解决方案咨询
PATCH请求跨域CORS异常问题
此前在相关提问中未找到明确解决方案,现重新整理问题及可复现步骤:
后端配置
搭建了一个简易Express服务器,代码如下:
const express = require('express') const methods = ['get', 'put', 'post', 'patch', 'delete'] const app = express() methods.forEach((method) => { const path = `/${method}-method-test` // 预检请求,路径相同但使用OPTIONS方法 app.options(path, (req, res) => { res.header('Access-Control-Allow-Origin', req.header('origin') ?? '*') res.header('Access-Control-Allow-Methods', `${method}, ${method.toUpperCase()}`) res.header('Access-Control-Allow-Headers', 'x-custom-request-header') res.end() }) // 实际接口 app[method](path, (req, res) => { res.header('Access-Control-Allow-Origin', req.header('origin') ?? '*') res.send(method) }) }) app.listen(5000, () => console.log('Methods test listening on http://localhost:5000'))
预检请求处理特性:
- 配置
Access-Control-Allow-Origin,允许任意源跨域 - 配置
Access-Control-Allow-Methods,同时允许指定方法的大小写形式(曾有人提及大小写可能引发问题) - 配置
Access-Control-Allow-Headers,允许自定义请求头x-custom-request-header
实际接口特性:
- 配置
Access-Control-Allow-Origin,允许任意源跨域 - 配置
Access-Control-Expose-Headers,允许客户端接收自定义响应头
上述配置均遵循CORS规范。
前端测试
编写浏览器端测试用例:
describe('Http methods', () => { const methods = ['get', 'put', 'post', 'patch', 'delete'] methods.forEach((method) => describe(method, () => { // 尝试发送简单请求(无预检请求,直接访问接口) it(`should allow a simple ${method} request in the browser`, async () => { const response = await fetch(`http://localhost:5000/${method}-method-test`, { method }) const body = await response.text() chai.expect(body).to.be.eq(method) }) // 通过自定义请求头强制触发预检请求 it(`should allow ${method} request with forced pre-flight request`, async () => { const response = await fetch(`http://localhost:5000/${method}-method-test`, { method, headers: { 'x-custom-request-header': 'hi' }, }) const body = await response.text() chai.expect(body).to.be.eq(method) }) }), ) })
测试逻辑:先验证无额外配置的简单请求,再通过自定义请求头触发预检请求进行验证。
测试结果
所有请求方法测试均正常通过,仅PATCH请求例外。Chrome和Firefox中均出现同一现象:浏览器未尝试为PATCH请求发送预检请求。
但使用API调试工具Insomnia测试相同请求时,接口可正常响应,预检请求与实际请求的响应头均符合预期:
问题总结
- 涉及CORS时,
PATCH请求有何特殊之处? - 是否有相关规范文档说明?
- Express是否存在针对
PATCH请求的异常处理逻辑? - 如何解决该跨域问题?
内容的提问来源于stack exchange,提问作者Balázs Édes
相关产品推荐
相关产品推荐

