使用apifox测试的时候正常,但是前端访问时不仅出现跨域错误,还出现了预检请求和403。
1.后端
首先我确定了后端确实配置了跨域
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")//项目中的所有接口都支持跨域
.allowedOriginPatterns("*")//所有地址都可以访问,也可以配置具体地址
.allowCredentials(true)
.allowedMethods("GET","POST","PUT","OPTIONS","DELETE","PATCH")//"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"
.allowedHeaders("*")//允许自定义请求头
.maxAge(3600);// 跨域允许时间
}
}
2.前端
前端配置了自定义请求头(导致预检请求的真实原因)
if (config.url !== '/user/login') {
// 非登录请求才添加请求头
if (token) {
config.headers.Authorization = 'Bearer ' + token
}
}
用Apifox测试的时候正常并没有出现403和跨域,由于后端使用了Spring Security,我想可能是Spring Security导致的403 forbidden禁止访问,
3.解决:
1.后端过滤器增加允许预检请求(options)
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//允许预检请求
if ("OPTIONS".equals(request.getMethod())) {
filterChain.doFilter(request, response);
return;
}
//获取token
String header = request.getHeader("Authorization");
......
2.Spring Security配置中添加允许OPTIONS
.antMatchers(HttpMethod.OPTIONS).permitAll()