-
一、背景
1、postman模拟跨域测试接口没问题,
2、前端页面跨域访问后端服务报跨域问题;
3、后台服务已经配置了跨域白名单; -
二、postman截图

-
三、前端调后端返回报错:
com.accenture.repairjob.poc.common.config.AuthFilterConfig.AuthFilter.getHandlerMethod:class org.springframework.web.servlet.handler.
AbstractHandlerMapping$ PreFlightHandler cannot be cast to class org.springframework.web.method.HandlerMethod (org.springframework.web.servlet.handler.AbstractHandlerMapping$PreFlightHandler and org.springframework.web.method.HandlerMethod are in unnamed module of loader org.springframework.boot.loader.LaunchedURLClassLoader @5ce65a89) -
四、页面端报错截图
post预检请求报错,正式请求自然也报错;XXX has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

-
五、分析
1、从报错信息看,是将PreFlightHandler 强转成HandlerMethod导致的报错;
2、代码中handlerMapping根据HttpServletRequest获取HandlerExecutionChain调用链,再根据调用链获取Handler。
而获得的Handler有可能获取到PreFlightHandler ,这时再强转就会报错;HandlerExecutionChain handlerChain = handlerMapping.getHandler(request); if (handlerChain != null) { handler = (HandlerMethod)handlerChain.getHandler(); } -
六、解决方法 :在强转之前先判断一下
if (!(handlerMethod instanceof HandlerMethod)) { return false; }
跨域报错:AbstractHandlerMapping$PreFlightHandler cannot be cast to class HandlerMethod are in unnamed
最新推荐文章于 2025-08-28 15:55:20 发布
本文主要讨论了一个前端跨域请求后端API时遇到的问题,即postman测试正常,但实际页面访问时出现跨域错误。问题源于后端代码尝试将PreFlightHandler转换为HandlerMethod导致的类型转换异常。分析了错误原因,并提出了在强转前增加类型判断的解决方法。
2458

被折叠的 条评论
为什么被折叠?



