-
一、背景
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; }