前后端分离处理数据的时候 常常会遇到跨域问题处理
后端处理跨域要分工具和类型(假装是这样,实际上没有什么区别)
idea创建项目的时候,可以不用配置运行工具 直接就是内部工具运行
这就需要多配置一个配置文件 不多说直接上代码
显示配置跨域 此处配置完了后,如果能正常运行则无需后面配置
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Administrator on 2017/7/26.
*/
@Configuration
public class AccessFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE,OPTIONS");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization,token");
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
如果上面不能正常运行则需要下面配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
* @Author: cq
* @Date: 2020/9/22 14:56
* @Version 1.0
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 配置所有请求
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
这种配置是比较懒的配置。其实springboot里面也集合了跨域问题,只需要一个注解
@CrossOrigin(origins = "*")
但是第二种方案需要每个接口都加注解 出于统一处理的便捷性还是加个过滤器吧
以上两种种亲测都可行
但是问题来了 如果以上方式加了还报错 并且response的header正常 错误如下
Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
原因就是浏览器的预检请求失败 即option请求失败 需要后端放行option请求即可
在spring security放行option请求
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
https://blog.csdn.net/weixin_45059597/article/details/107490252?utm_source=app