1. 程式人生 > >SpringBoot rest-api+Vue CORS跨域.md

SpringBoot rest-api+Vue CORS跨域.md

跨域,指的是瀏覽器不能執行其他網站的指令碼。它是由瀏覽器的同源策略造成的,是瀏覽器對JavaScript施加的安全限制。

目前用到兩種方式

  1. 前後端統一通過代理轉發,使api和vue web都通過同一域名+埠來訪問,以確保同源;
  2. 通過服務端介面層配置,支援CORS請求;

服務層配置

我們目前前端有Vue、安卓、iOS,後端共用一套,因此更好的方式是通過修改服務層,以支援多端請求。

Spring MVC配置方式

Spring MVC從4.2版本開始增加對CORS的支援,只需要在Controller或Method上新增@CrossOrigin註解即可,該註解在SpringBoot上新增無效。

@CrossOrigin(origins = "*", maxAge = 3600)  
@RestController 

或者:

# CORSFilter
@Component
public class CORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    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-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}
}

# web.xml
<filter>
  <filter-name>cors</filter-name>
  <filter-class>com.web.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

SpringBoot配置方式

@Configuration
public class CustomCorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允許任何域名使用
        corsConfiguration.addAllowedOrigin("*");
        // 允許任何頭
        corsConfiguration.addAllowedHeader("*");
        // 允許任何方法(post、get等)
        corsConfiguration.addAllowedMethod("*");
        // 允許傳送Cookie
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }
}

或者:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("*")
            .allowedHeaders("*")
            .allowCredentials(true).maxAge(3600);
    }
}

查閱:https://blog.csdn.net/z69183787/article/details/53102112