先後分離調用API跨域

先後分離調用API接口跨域問題

 

什麼是跨域?

 

   跨域是指一個域下的文檔或腳本試圖去請求另外一個域下的資源,這裏跨域是廣義的。web

 

廣義的跨域:

  1. 資源跳轉:A連接、重定向、表單提交。
  2. 資源嵌入: <link>、<script>、<img>、<frame>等dom標籤,還有樣式中background:url()、@font-face()等文件外鏈。
  3. 腳本請求: js發起的ajax請求、dom和js對象的跨域操做等。

 

  其實咱們一般所說的跨域是狹義的,是由瀏覽器同源策略限制的一類請求場景。ajax

 

什麼是同源策略?

  同源策略/SOP(Same origin policy)是一種約定,由Netscape公司1995年引入瀏覽器,它是瀏覽器最核心也最基本的安全功能,若是缺乏了同源策略,瀏覽器很容易受到XSS、CSFR等攻擊。所謂同源是指"協議+域名+端口"三者相同,即使兩個不一樣的域名。spring

  

同源策略限制如下幾種行爲:

  1. Cookie、LocalStorage 和 IndexDB 沒法讀取。
  2. DOM 和 Js對象沒法得到。
  3. AJAX 請求不能發送

 

跨域場景:

  

url跨域

說明 是否容許通訊

http://www.domain.com/a.js瀏覽器

http://www.domain.com/b.js安全

http://www.domain.com/lab/c.jscors

同一域名,不一樣文件或路徑 容許

http://www.domain.com:8000/a.jsdom

http://www.domain.com/b.jsurl

同一域名,不一樣端口 不容許

http://www.domain.com/a.jsspa

https://www.domain.com/b.js

同一域名,不一樣協議 不容許

http://www.domain.com/a.js

http://192.168.4.12/b.js

域名和域名對應相同ip 不容許

http://www.domain.com/a.js

http://x.domain.com/b.js

http://domain.com/c.js

主域相同,子域不一樣 不容許

http://www.domain1.com/a.js

http://www.domain2.com/a.js

不一樣域名 不容許

  

 

解決方式:(這裏只介紹一種最簡單的方式)

 

 

跨域資源共享(CORS)

  SpringBoot新增WebMvcConfiguration類

 

package com.yhzy.zytx.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @ClassName WebMvcConfiguration
 * @Description 跨域請求處理
 * @Author 天生傲骨、怎能屈服
 * @Date 2019/5/31 16:19
 * @Version 1.0
 */
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        /*是否容許請求帶有驗證信息*/
        corsConfiguration.setAllowCredentials(true);
        /*容許訪問的客戶端域名*/
        corsConfiguration.addAllowedOrigin("*");
        /*容許服務端訪問的客戶端請求頭*/
        corsConfiguration.addAllowedHeader("*");
        /*容許訪問的方法名,GET POST等*/
        corsConfiguration.addAllowedMethod("*");
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}

 

 

 

  

  注:類上要加@Configuration註解

 

  這樣就OK了,超簡單,感謝各位大佬閱讀,不喜勿噴!!!

相關文章
相關標籤/搜索