java拦截器跨域报错$PreFlightHandler cannot be cast to class org.springframework.web.method.HandlerMethod

1、问题描述

作者在写 springboot 项目时发生了这个样一个错误,在非跨域请求测试中没有出现,但是在跨域请求测试时出现了问题( ... has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.)。

错误提示

报错内容是拦截器中的这句话、hander 的类型转化错误。

HandlerMethod handlerMethod = (HandlerMethod) handler;

2、问题的解决:

这里只需要在这句话前加入一个判断就好

if (!(handler instanceof HandlerMethod)) {
    return false;
}
HandlerMethod handlerMethod = (HandlerMethod) handler;

3、问题原因的猜想

对于 json 传输的跨域是一个复杂跨域,可以在前端控制台看到进行了两次请求,一次是 "预请求" 用于判断是否支持跨域,一次是正式传输数据的请求。
两次请求

可以看见有一次请求返回了 500,返回 500 的应该是跨域的 "预请求",当他返回失败之后,带有参数请求应该中断。果然,另一个请求没有返回。所以作者推测是 handler 在“预请求”中不能被转化为 HandlerMethod。所以只需要单独判断一下 handler 能不能进行类型转化就行了。

4、配置跨域

都写到这里了,顺便把跨域的配置也记录一下,作者的 springboot 版本是 2.3.1,测试使用拦截器失败了,最后使用了过滤器终结了跨域的配置。

package com.xxx.demo.config;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "CorsFilter")
@Configuration
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin","*"); // 允许的来源
response.setHeader("Access-Control-Allow-Credentials", "true"); // 是否允许证书
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT"); // 允许的请求方式
response.setHeader("Access-Control-Max-Age", "3600"); // 预检请求的有效期
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
}

参考:
https://segmentfault.com/a/1190000019550329?utm_source=tag-newest

https://www.cnblogs.com/qunxiadexiaoxiangjiao/p/9446956.html

结语:跨域爸爸放过我吧。