SpringBoot服務(wù)器端解決跨域問題
本文導(dǎo)航
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'; }}
指定請求來源,可以寫成“*”,表示接收所有來源的請求。
第二種方式:
@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping('/**').allowedOrigins('http://localhost:8081') .allowedHeaders('*') .allowedMethods('*') .maxAge(30*1000); }}
allowOrigins也可以寫成allowedOrigins(' * '),表示接收所有來源的請求。
注意點(diǎn):
1、路徑來源的寫法問題
如果后臺(tái)指定路徑來源為:http://localhost:8081
那么在瀏覽器里訪問前端頁面的時(shí)候,必須用 http://localhost:8081,不可以寫成127.0.0.1或者本機(jī)ip地址。否則還是會(huì)報(bào)跨域錯(cuò)誤。測試如下
后臺(tái)設(shè)置:
@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>
啟動(dòng)服務(wù),瀏覽器里訪問:
http://localhost:8081/index.html
正常返回結(jié)果
瀏覽器里訪問:
http://127.0.0.1:8081/index.html
報(bào)跨域錯(cuò)誤如下:
所以說,瀏覽器訪問路徑需要與后臺(tái)allowOrigin里設(shè)置的參數(shù)一致。
那如果代碼里的訪問路徑可以不一樣嗎,比如:
doGet = function () { $.get(’http://127.0.0.1:8080/hello’, function (msg) { //本機(jī)ip地址 $('#app').html(msg); }); } doPut = function () { $.ajax({ type:’put’, url:’http://192.168.1.26:8080/doPut’, success:function (msg) { $('#app').html(msg); } }) }
經(jīng)過測試,是可以的,只要瀏覽器里訪問頁面的路徑寫法與后臺(tái)保持一致就可以了。
2、攜帶Cookie
有時(shí)候,前端調(diào)用后端接口的時(shí)候,必須要攜帶cookie(比如后端用session認(rèn)證),這個(gè)時(shí)候,就不能簡單的使用allowOrigins('*')了,必須要指定具體的ip地址,否則也會(huì)報(bào)錯(cuò)。
以上就是SpringBoot服務(wù)器端解決跨域問題的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 解決跨域的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))2. IntelliJ IDEA創(chuàng)建web項(xiàng)目的方法3. 原生JS實(shí)現(xiàn)記憶翻牌游戲4. Python寫捕魚達(dá)人的游戲?qū)崿F(xiàn)5. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼6. Android studio 解決logcat無過濾工具欄的操作7. django創(chuàng)建css文件夾的具體方法8. ASP.NET MVC通過勾選checkbox更改select的內(nèi)容9. ASP中實(shí)現(xiàn)字符部位類似.NET里String對(duì)象的PadLeft和PadRight函數(shù)10. Django如何繼承AbstractUser擴(kuò)展字段
