欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring boot 總結(jié)之跨域處理cors的方法

 更新時(shí)間:2018年02月07日 16:50:50   作者:花_現(xiàn)  
本篇文章主要介紹了Spring boot 總結(jié)之跨域處理cors的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

背景

現(xiàn)在做的很多項(xiàng)目都是前后端分離的,這就引出一個(gè)很常見的問題,我們的頁(yè)面和接口是在不同域名下的,當(dāng)我們通過ajax訪問后端接口的時(shí)候就會(huì)出現(xiàn)跨域問題,這種問題我們?cè)趺唇鉀Q呢?一般來說就是cors和jsonp這兩種方案。Spring簡(jiǎn)化了cors的配置,接下來我們來看一下它提供的cors。

跨域問題描述

Web開發(fā)經(jīng)常會(huì)遇到跨域問題,解決方案有:jsonp,iframe,CORS等等。

CORS 與 JSONP 相比:

1、 JSONP 只能實(shí)現(xiàn) GET 請(qǐng)求,而 CORS 支持所有類型的 HTTP 請(qǐng)求。
2、 使用 CORS,開發(fā)者可以使用普通的 XMLHttpRequest 發(fā)起請(qǐng)求和獲得數(shù)據(jù),比起 JSONP 有更好的 錯(cuò)誤處理。
3、 JSONP 主要被老的瀏覽器支持,它們往往不支持 CORS,而絕大多數(shù)現(xiàn)代瀏覽器都已經(jīng)支持了 CORS。

WebMvcConfigurer對(duì)象

我們可以初始化一個(gè)WebMvcConfigurer對(duì)象來配置我們的cors映射。

@Configuration
public class CorsCongiguration {
  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**"); // 允許所有第三方域名訪問該接口
        // .allowedOrigins("http://domain2.com")//指定來源域名
        // .allowedMethods("PUT", "DELETE")
        // .allowedHeaders("header1", "header2", "header3")
        // .exposedHeaders("header1", "header2")
        // .allowCredentials(false).maxAge(3600);
      }
    };
  }
}

繼承WebMvcConfigurerAdapter

這種方式跟上面的方式很類似

@Configuration
@EnableWebMvc
public class CorsConfiguration_2 extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**");
  }
}

corsFilter

這種方式現(xiàn)在很少用

@Component
@EnableWebMvc
public class CorsFilterCongiguration extends CorsFilter {

  public CorsFilterCongiguration(CorsConfigurationSource configSource) {
    super(configSource);
  }

  @Bean
  public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
//    config.addAllowedOrigin("http://domain1.com");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/api/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0); // 必須在所有Filter之前
    return bean;
  }

}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論