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

Cask Undertow服务器带Bearer Token的CORS请求报405错误求助

解决Cask Undertow服务器带Bearer Token的CORS预检405错误

问题核心

带Authorization头的CORS请求会触发浏览器发送OPTIONS预检请求,当前配置虽添加了CORS响应头,但未正确处理OPTIONS请求的生命周期,导致默认的handleMethodNotAllowed返回405错误;同时代码存在拼写错误,会导致允许的请求头配置不生效。

修复步骤

  1. 优先处理OPTIONS预检请求:在handleRequest方法中先判断请求方法是否为OPTIONS,若是直接返回200响应,无需走后续路由逻辑
  2. 修正拼写错误:将acccessControlAllowHeaders改为正确的accessControlAllowHeaders(原代码多了一个字母c)

修改后的完整CorsHandler代码

class CorsHandler(dispatchTrie: DispatchTrie[Map[String, (Routes, EndpointMetadata[_])]],
                  mainDecorators: Seq[Decorator[_, _, _]],
                  debugMode: Boolean,
                  handleNotFound: () => Response.Raw,         
                  handleMethodNotAllowed: () => Response.Raw,         
                  handleError: (Routes, EndpointMetadata[_], Result.Error) => Response.Raw)
extends Main.DefaultHandler(dispatchTrie, mainDecorators, debugMode, handleNotFound, handleMethodNotAllowed, handleError)(CorsHandler.log) {
    import CorsHandler._
    override def handleRequest(exchange: HttpServerExchange): Unit = {        
        // 先处理OPTIONS预检请求,直接返回200完成响应
        if (exchange.getRequestMethod == Methods.OPTIONS) {
            exchange.getResponseHeaders
                .put(accessControlAllowOrigin, "http://localhost:3000")
                .put(accessControlAllowCredentials, accepted)
                .put(accessControlAllowMethods, "POST,GET,PUT,DELETE,PATCH,HEAD,OPTIONS")
                .put(accessControlAllowHeaders, "Origin,Accept,Authorization,Content-Type,X-Requested-With")
            exchange.setStatusCode(200)
            exchange.endExchange()
            return
        }
        
        // 为正常请求添加CORS响应头
        exchange.getResponseHeaders
            .put(accessControlAllowOrigin, "http://localhost:3000")
            .put(accessControlAllowCredentials, accepted)
            .put(accessControlAllowMethods, "POST,GET,PUT,DELETE,PATCH,HEAD,OPTIONS")
            .put(accessControlAllowHeaders, "Origin,Accept,Authorization,Content-Type,X-Requested-With")     
        
        super.handleRequest(exchange)
    }
}

补充说明

  • 预检请求不需要执行实际业务逻辑,直接返回200即可,浏览器会根据返回的CORS头判断是否允许发送实际请求
  • 必须确保accessControlAllowHeaders包含Authorization,否则浏览器会因为请求头不在允许列表中而拒绝发送请求
  • Postman/curl不会触发浏览器的预检机制,因此能正常调用;移除Authorization头后,请求属于简单请求范畴,也不会触发预检,所以能正常响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 00:23:24