OPTIONS 请求404或被忽略是因为路由未显式注册,Go标准库和多数轻量路由不自动处理预检;需手动添加OPTIONS处理器或使用rs/cors等中间件。
OPTIONS 请求会 404 或被忽略Go 的标准 http.ServeMux 和多数轻量路由(如 gorilla/mux 默认配置)不会自动响应预检请求。浏览器在发送带认证、自定义头或非简单方法(如 PATCH、PUT)的请求前,会先发一个 OPTIONS 请求。如果服务端没显式注册该路径的 OPTIONS 处理器,就直接 404 —— 这不是 CORS 配置问题,是路由缺失。
http.HandleFunc("POST /api/user", ...),但没写 http.HandleFunc("OPTIONS /api/user", ...)
curl -X OPTIONS -I http://localhost:8080/api/user 测试,看是否返回 200 或 405gin,需确保调用了 r.OPTIONS(...);若用 echo,要启用 CORS 中间件并允许预检OPTIONS 响应预检响应不需要业务逻辑,只需返回正确头和 200 状态。关键是设置 Access-Control-Allow-Methods、Access-Control-Allow-Headers 与实际请求匹配,否则浏览器仍会拒绝后续请求。
func preflightHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "https://example.com")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Expose-Headers", "Content-Length")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Max-Age", "86400")
// 预检必须返回 200,不能是 204
w.WriteHeader(http.StatusOK)
}
Access-Control-Allow-Origin 不能为 * + Acc
ess-Control-Allow-Credentials: true,否则浏览器报错Access-Control-Allow-Headers 必须包含前端实际发送的自定义头(比如 X-User-ID),漏一个就会失败w.WriteHeader(http.StatusNoContent) —— 部分浏览器要求预检响应有 body(哪怕空)rs/cors 库避免重复造轮子手写预检逻辑易出错,推荐使用成熟中间件。官方推荐的 github.com/rs/cors 能自动拦截并响应预检,且支持细粒度控制。
import "github.com/rs/cors"
handler := http.HandlerFunc(yourHandler)
corsHandler := cors.New(cors.Options{
AllowedOrigins: []string{"https://example.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
ExposedHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 86400,
}).Handler(handler)
http.ListenAndServe(":8080", corsHandler)
OPTIONS 时自动返回预检响应,无需额外注册路由AllowedOrigins 支持通配符(如 https://*.example.com)和函数动态判断cors 必须放在最外层,否则预检可能被下游中间件拦截浏览器 Network 面板里看到 OPTIONS 请求状态是 canceled 或红字?说明预检根本没发出 —— 往往是前端发的请求本身触发不了预检(比如 Content-Type 是 application/json 但没带认证头),或是服务端连 OPTIONS 路由都没注册。
Content-Type 不是 application/x-www-form-urlencoded、multipart/form-data、text/plain 三者之一)+ 带 Authorization 头 + 自定义头 + 非 GET/HEAD/POST 方法curl -H "Origin: https://example.com" -H "Access-Control-Request-Method: POST" -H "Access-Control-Request-Headers: Content-Type" -X OPTIONS -I http://localhost:8080/api 模拟预检Access-Control-Allow-Origin,且值与请求头 Origin 完全一致(包括协议、端口)预检不是“开了 CORS 就完事”,它是浏览器和服务端之间一次严格的契约协商。漏掉一个头、写错一个 origin、多加一个空格,都会让整个请求链断在第一步。