本文主要是介绍Spring Boot如何解决前端的Access-Control-Allow-Origin跨域问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
当我们在做前后端分离的开发时,在使用fetch交换数据的时候,提示Access-Control-Allow-Origin跨域问题,解决方案跟客户端没关系,修改的是服务端。
一、在过滤器中设置响应头:
@WebFilter(filterName = "CorsFilter ")
public class CorsFilter implements Filter {@Overridepublic void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse response = (HttpServletResponse) res;HttpServletRequest reqs = (HttpServletRequest) req;// response.setHeader("Access-Control-Allow-Origin",reqs.getHeader("Origin"));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);}@Overridepublic void init(FilterConfig filterConfig) {}@Overridepublic void destroy() {}}
二、在spring boot 服务中心添加一个配置文件:
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS").allowCredentials(true).maxAge(3600);}
}
这篇关于Spring Boot如何解决前端的Access-Control-Allow-Origin跨域问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!