1. 什么是跨域
從不同的地址訪問另外一個地址就是跨域
2.跨域一定會有異常嗎
跨域異常只會在前端發生,后端跨域不會產生異常
因為瀏覽器有一個叫做同源策略的東西,它發現不同域之間的訪問是不安全的行為,會禁止,所以會拋出異常
3.五種解決跨域的方式
1. 跨域請求JSONP
前端配置
$.agax({url:’http://localhost:8080/cors/jsonp/1’,dataType:"jsonp",//jsonp:'a',不指定默認callback//jsonpCallback:"cc",不指定自動生產type:'GET',success:function(){alert(result.data);}});
后端配置:
@GetMapp("cors/jsonp/{id}")
public JSONObject getUser(@PathVariable Integer id,String callback){User user=new User("xushu","jsonp");return new JSONPObject(callback,new Resule<>(200,"SUCCESS",user))
}
好處:兼容各種瀏覽器
弊端:前端端都需要配置-耦合度高
2. 跨域請求cors【單一】
注意:需要用到@CrossOrigin注解
前端配置
$.agax({url:’http://localhost:8080/cors/1’,type:'GET',success:function(){alert(result.data);}});
后端配置:
@GetMapp("cors/{id}")
@CrossOrigin("http://localhost:8081")
public JSONObject getUser(@PathVariable Integer id){User user=new User("xushu","jsonp");return new Resule<>(200,"SUCCESS",user);
}
注解:只支持單一的接口
3. 跨域請求cors【批量】
注意:后端需要實現WebMvcConfigurer
后端配置:
public class MyWebMvcConfigurer implements WebMvcConfigurer{@Overridepublic void addCorsMappings(CorsRegistry registry){registry.addMapping("user/*")//配置那些接口可以跨域.allowedOrigins("http://localhost:8080")//配置那些來源有權跨域.allowedMethods("GET","POST","DELETE","PUT");//配置運行跨域訪問方法};
}
4. 跨域請求cors【所有】
注意:后端需要配置過濾器
后端配置:
@Configuration
public class MyCorsFilter{//@Beanpublic CorsFilter corsFilter(){//1.創建CORS配置對象CorsConfiguration config=new CorsConfiguration();//支持域名config.addAllowedOriginPattern("*");//是否發送cookieconfig.setAllowCredentials(true);//支持請求方式config.addAllowedMethod("*");//添加地址映射UrlBasedCorsConfigurationSource corsConfigurationSource=new UrlBasedCorsConfigurationSource ();corsConfigurationSource.registerCorsConfiguration("/**",config);//返回corsFilter對象return new CorsFilter(corsConfigurationSource);}
}
優缺點:
優點:前端不需要寫代碼就可以支持,主要靠服務器進行配置**
缺點:IE瀏覽器不能低于IE10,瀏覽器一旦發現AJAX請求跨域,就會自動添加一些附加的頭信息,有時還會多出一次附加的請求,但用戶不會有感覺【option請求】