springboot2.0设置跨域没效果

2022-07-03 11:06:46

springboot2.0设置跨域没效果

  1. 可能原因1:没有设置允许跨域
@ConfigurationpublicclassCrosConfigimplementsWebMvcConfigurer{@OverridepublicvoidaddCorsMappings(CorsRegistry registry){
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*").allowCredentials(true).exposedHeaders("").maxAge(3600);}}
  1. 代码执行顺序,您可能在拦截器或者其他地方设置了跨域的代码,但是代码是先执行过滤器,所以会有跨域的问题
    所以需要在过滤器中设置跨域的问题
import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;import org.springframework.http.HttpMethod;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Component;import javax.servlet.*;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;/**
 * @author Administrator
 */@Component@Order(Ordered.HIGHEST_PRECEDENCE)publicclassSimpleCORSFilterimplementsFilter{@OverridepublicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException{

        HttpServletResponse response=(HttpServletResponse) res;
        HttpServletRequest request=(HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Headers","*");if(request.getMethod().equals(HttpMethod.OPTIONS.name())){
            response.setStatus(HttpStatus.NO_CONTENT.value());}else{
            chain.doFilter(req, res);}}@Overridepublicvoidinit(FilterConfig filterConfig){}@Overridepublicvoiddestroy(){}}
  • 作者:倒霉鬼^
  • 原文链接:https://blog.csdn.net/weixin_44021888/article/details/111183129
    更新时间:2022-07-03 11:06:46