spring boot / cloud (六) 開啟CORS跨域訪問


spring boot / cloud (六) 開啟CORS跨域訪問

前言

什么是CORS?

Cross-origin resource sharing(跨域資源共享),是一個W3C標准,它允許你向一個不同源的服務器發出XMLHttpRequest請求,從而克服了ajax只能請求同源服務的限制.並且也可以通過靈活的設置,來指定什么樣的請求是可以被授權的.

什么是跨域?

假設你在http://xxx.com/test/下有一個js文件,從這個js里發出一個ajax請求請求后端服務,按照如下情況判定:

請求地址 原因 結果
http://xxx.com/xxxx/action 同一域名,不同文件夾 非跨域
http://xxx.com/test/action 同一域名,同一文件夾 非跨域
http://a.xxx.com/test/action 不同域名,文件路徑相同 跨域
http://xxx.com:8080/test/action 同一域名,不同端口 跨域
https://xxx.com/test/action 同一域名,不同協議 跨域

還有那些其他的跨域解決方案?

  • JSONP : 動態添加一個<script>標簽,而script標簽的src屬性是沒有跨域的限制的。這樣說來,這種跨域方式其實與ajax XmlHttpRequest協議無關了,而缺點也很明顯,它只支持GET請求而不支持POST等其它類型的HTTP請求;它只支持跨域HTTP請求這種情況,不能解決不同域的兩個頁面之間如何進行JavaScript調用的問題

  • NGINX代理 : 通過一個代理服務器,將跨域的請求轉發,如:前端JS在http://www.demo.com/a.js,后端是http://www.abc.com/app/action,通過代理可將后端的地址轉換成http://www.demo/app/action,這樣,從前端發起的請求,就不存在跨域的情況了

然后CORS是支持所有類型的HTTP請求,並且也只是服務端進行設置即可,但是缺點就是老的瀏覽器不支持CORS(如:IE7,7,8,等)

思路

CORS的響應頭

  • Access-Control-Allow-Origin : 必須的,允許的域名,如果設置*,則表示接受任何域名

  • Access-Control-Allow-Credentials : 非必須的,表示是否允許發送Cookie,注意,當設置為true的時候,客戶端的ajax請求,也需要將withCredentials屬性設置為true

  • Access-Control-Expose-Headers : 非必須的,表示客戶端能拿到的header,默認情況下XMLHttpRequestgetResponseHeader方法只能拿到幾個基本的header,如果有自定義的header要獲取的話,則需要設置此值

  • Access-Control-Request-Method : 必須的,表示CORS上會使用到那些HTTP方法

  • Access-Control-Request-Headers : 必須的,表示CORS上會有那些額外的的有信息

CORS將請求分為兩種類型

兩種類型分別為簡單請求非簡單請求,同時滿足以下兩大條件的請求被定義為是簡單請求:

  • 請求方法是以下三種之一:

  • HEAD

  • GET

  • POST

  • HTTP頭信息不超出以下幾種字段:

  • Accept

  • Accept-Language

  • Content-Language

  • Last-Event-ID

  • Content-Type:只限於三個值application/x-www-form-urlencoded、multipart/form-data、text/plain

對於非簡單請求,瀏覽器會自動發一個預檢請求,這個請求是OPTIONS方法的,主要是詢問服務器當前請求是否在允許范圍內

實現

1.方式A:使用@CrossOrigin來標記指定的方法(小范圍跨域)

@RequestMapping(value = "add", method = RequestMethod.GET)
@CrossOrigin(methods = { RequestMethod.GET, RequestMethod.POST }, origins = "*")
public RestResponse<Integer> add(Integer a, Integer b) {
    return new RestResponse<>(demoService.add(a, b));
}

2.方式B:使用spring boot的默認配置來設定全局跨域

endpoints.cors.allow-credentials=
endpoints.cors.allowed-headers=
endpoints.cors.allowed-methods=GET
endpoints.cors.allowed-origins=
endpoints.cors.exposed-headers=
endpoints.cors.max-age=1800

3.方式C:使用WebMvcConfigurer自定義配置跨域

定義CorsRegistrationConfig類

public static class CorsRegistrationConfig {
    //描述 : 掃描地址
    private String mapping = "/**";
    //描述 : 允許證書
    private Boolean allowCredentials = null;
    //描述 : 允許的域
    private String allowedOrigins = "*";
    //描述 : 允許的方法
    private String allowedMethods = "POST,GET,DELETE,PUT";
    //描述 : 允許的頭信息
    private String allowedHeaders = "*";
    
    .........省略
}

定義CorsConfig類

@Configuration
@ConfigurationProperties(prefix = "org.itkk.cors")
@Validated
public class CorsConfig {

  //描述 : 跨域信息
  @NotNull
  private Map<String, CorsRegistrationConfig> config;
  
  .....省略

}

定義重寫addCorsMappings方法

  @Bean
  public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        //掃描地址
        if (!CollectionUtils.isEmpty(config)) {
          Iterator<String> keys = config.keySet().iterator();
          while (keys.hasNext()) {
            String key = keys.next();
            CorsRegistrationConfig item = config.get(key);
            CorsRegistration cr = registry.addMapping(item.getMapping());
            if (item.getAllowCredentials() != null) {
              cr.allowCredentials(item.getAllowCredentials());
            }
            if (StringUtils.isNotBlank(item.getAllowedOrigins())) {
              String[] allowedOriginArray = item.getAllowedOrigins().split(",");
              cr.allowedOrigins(allowedOriginArray);
            }
            if (StringUtils.isNotBlank(item.getAllowedMethods())) {
              String[] allowedMethodArray = item.getAllowedMethods().split(",");
              cr.allowedMethods(allowedMethodArray);
            }
            if (StringUtils.isNotBlank(item.getAllowedHeaders())) {
              String[] allowedHeaderArray = item.getAllowedHeaders().split(",");
              cr.allowedHeaders(allowedHeaderArray);
            }
          }
        }
      }
    };
  }

配置文件,可根據不同的mapping設置不同的cors規則

org.itkk.cors.config.demo.mapping=/**
org.itkk.cors.config.demo.allowCredentials=
org.itkk.cors.config.demo.allowedOrigins=
org.itkk.cors.config.demo.allowedMethods=
org.itkk.cors.config.demo.allowedHeaders=

使用jquery,在跨域場景下進行測試

    $(function(){
		$.ajax({
            url:'http://127.0.0.1:8080/demo/c',
            headers:{
                'aheader':'111'
            },
            type:'GET',
            dataType:'json',
            success:function(data){
                console.log(1);
                console.log(data);
                console.log(2);

            }
        });
    });

代碼倉庫 (博客配套代碼)

結束

演示了單spring boot的應用的,在后續的章節中,會找機會寫一下在微服務場景下(spring cloud)的跨域設置


想獲得最快更新,請關注公眾號

想獲得最快更新,請關注公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM