本文導航
SpringBoot解決跨域問題的兩種方案:
1、通過給方法或者類加注解的形式,@CrossOrigin。
2、繼承接口,重寫addCorsMappings方法。
第一種方式:
@RestController @CrossOrigin("http://localhost:8081") public class BaseController { @GetMapping("/hello") public String testGet(){ return "get"; } @PutMapping("/doPut") public String testPut(){ return "put"; } }
指定請求來源,可以寫成“*”,表示接收所有來源的請求。
第二種方式:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:8081") .allowedHeaders("*") .allowedMethods("*") .maxAge(30*1000); } }
allowOrigins也可以寫成allowedOrigins(" * "),表示接收所有來源的請求。
注意點:
1、路徑來源的寫法問題
如果后台指定路徑來源為:http://localhost:8081
那么在瀏覽器里訪問前端頁面的時候,必須用 http://localhost:8081,不可以寫成127.0.0.1或者本機ip地址。否則還是會報跨域錯誤。測試如下
后台設置:
@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:8081") .allowedHeaders("*") .allowedMethods("*") .maxAge(30*1000); }
前端請求:
<script> doGet = function () { $.get('http://localhost:8080/hello', function (msg) { $("#app").html(msg); }); } doPut = function () { $.ajax({ type:'put', url:'http://localhost:8080/doPut', success:function (msg) { $("#app").html(msg); } }) } </script>
啟動服務,瀏覽器里訪問:
http://localhost:8081/index.html
正常返回結果
瀏覽器里訪問:
http://127.0.0.1:8081/index.html
報跨域錯誤如下:
所以說,瀏覽器訪問路徑需要與后台allowOrigin里設置的參數一致。
那如果代碼里的訪問路徑可以不一樣嗎,比如:
doGet = function () { $.get('http://127.0.0.1:8080/hello', function (msg) { //本機ip地址 $("#app").html(msg); }); } doPut = function () { $.ajax({ type:'put', url:'http://192.168.1.26:8080/doPut', success:function (msg) { $("#app").html(msg); } }) }
經過測試,是可以的,只要瀏覽器里訪問頁面的路徑寫法與后台保持一致就可以了。
2、攜帶Cookie
有時候,前端調用后端接口的時候,必須要攜帶cookie(比如后端用session認證),這個時候,就不能簡單的使用allowOrigins("*")了,必須要指定具體的ip地址,否則也會報錯。