完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题
作者:天工开物_152368
这篇文章主要介绍了完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
当我们在做前后端分离的开发时,在使用fetch交换数据的时候,提示Access-Control-Allow-Origin跨域问题,解决方案跟客户端没关系,修改的是服务端。
一、在过滤器中设置响应头:
@WebFilter(filterName = "CorsFilter ") public class CorsFilter implements Filter { @Override public 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); } @Override public void init(FilterConfig filterConfig) {} @Override public void destroy() {} }
二、在spring boot 服务中心添加一个配置文件:
@Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") .allowCredentials(true).maxAge(3600); } }
到此这篇关于完美解决Spring Boot前端的Access-Control-Allow-Origin跨域问题的文章就介绍到这了,更多相关springboot Access-Control-Allow-Origin跨域内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!