跨域:跨域名的訪問,是瀏覽器對ajax的一種限制,這樣能夠有效的防止跨站攻擊html
跨域的範疇: 域名不一樣 或 端口不一樣 或 二級域名不一樣前端
解決方案:java
第一種:因爲前端基礎薄弱,且該方式老掉牙,不講解;nginx
第二種:利用nginx的反向代理,使得咱們表面發送不跨域的請求,實際代理了跨域,配置nginx相關配置便可;ajax
第三種:CORS,規範化的跨域請求解決方案,在服務端進行控制是否容許跨域;跨域
詳解:瀏覽器會將ajax請求分爲兩類,其處理方案略有差別:簡單請求、特殊請求。瀏覽器
簡單請求:服務器
請求方法爲 : head get postcookie
Http的頭信息不能超過如下幾種字段:Accept Accept-Language Content-Language Last-Event-ID Content-Typecors
Access-Control-Allow-Origin: http://manage.hahaha.com //可接受的域,是一個具體域名或者*,表明任意
Access-Control-Allow-Credentials: true //是否容許攜帶cookie,默認狀況下,cors不會攜帶cookie,除非這個值是true Content-Type: text/html; charset=utf-8
服務的響應頭中須要攜帶Access-Control-Allow-Credentials而且爲true。
瀏覽器發起ajax須要指定withCredentials 爲true
響應頭中的Access-Control-Allow-Origin必定不能爲*,必須是指定的域名
複雜請求:
請求方式: put
@Configuration public class GlobalCorsConfig { @Bean public CorsFilter corsFilter() { //1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration(); //1) 容許的域,不要寫*,不然cookie就沒法使用了
config.addAllowedOrigin("http://manage.hahaha.com"); //2) 是否發送Cookie信息
config.setAllowCredentials(true); //3) 容許的請求方式
config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); // 4)容許的頭信息
config.addAllowedHeader("*"); //2.添加映射路徑,咱們攔截一切請求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource(); configSource.registerCorsConfiguration("/**", config); //3.返回新的CorsFilter.
return new CorsFilter(configSource); } }
摘自--某某筆記