国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

SpringBoot服務(wù)器端解決跨域問(wèn)題

瀏覽:97日期:2023-04-10 09:13:33

本文導(dǎo)航

SpringBoot解決跨域問(wèn)題的兩種方案:

1、通過(guò)給方法或者類加注解的形式,@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'; }}

指定請(qǐng)求來(lái)源,可以寫成“*”,表示接收所有來(lái)源的請(qǐng)求。

第二種方式:

@Configurationpublic class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping('/**').allowedOrigins('http://localhost:8081') .allowedHeaders('*') .allowedMethods('*') .maxAge(30*1000); }}

allowOrigins也可以寫成allowedOrigins(' * '),表示接收所有來(lái)源的請(qǐng)求。

注意點(diǎn):

1、路徑來(lái)源的寫法問(wèn)題

如果后臺(tái)指定路徑來(lái)源為:http://localhost:8081

那么在瀏覽器里訪問(wèn)前端頁(yè)面的時(shí)候,必須用 http://localhost:8081,不可以寫成127.0.0.1或者本機(jī)ip地址。否則還是會(huì)報(bào)跨域錯(cuò)誤。測(cè)試如下

后臺(tái)設(shè)置:

@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping('/**').allowedOrigins('http://localhost:8081') .allowedHeaders('*') .allowedMethods('*') .maxAge(30*1000); }

前端請(qǐng)求:

<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ù),瀏覽器里訪問(wèn):

http://localhost:8081/index.html

正常返回結(jié)果

瀏覽器里訪問(wèn):

http://127.0.0.1:8081/index.html

報(bào)跨域錯(cuò)誤如下:

SpringBoot服務(wù)器端解決跨域問(wèn)題

所以說(shuō),瀏覽器訪問(wèn)路徑需要與后臺(tái)allowOrigin里設(shè)置的參數(shù)一致。

那如果代碼里的訪問(wèn)路徑可以不一樣嗎,比如:

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)過(guò)測(cè)試,是可以的,只要瀏覽器里訪問(wèn)頁(yè)面的路徑寫法與后臺(tái)保持一致就可以了。

2、攜帶Cookie

有時(shí)候,前端調(diào)用后端接口的時(shí)候,必須要攜帶cookie(比如后端用session認(rèn)證),這個(gè)時(shí)候,就不能簡(jiǎn)單的使用allowOrigins('*')了,必須要指定具體的ip地址,否則也會(huì)報(bào)錯(cuò)。

以上就是SpringBoot服務(wù)器端解決跨域問(wèn)題的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 解決跨域的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 宜川县| 合江县| 台南市| 喀什市| 轮台县| 仪征市| 崇信县| 宣汉县| 崇州市| 马边| 惠东县| 瑞丽市| 阿坝| 滕州市| 石首市| 株洲县| 泗洪县| 甘谷县| 鄂州市| 灵寿县| 河南省| 大城县| 湘潭市| 山东省| 手游| 民丰县| 舒兰市| 佳木斯市| 共和县| 潮安县| 嵩明县| 北海市| 韩城市| 北海市| 尤溪县| 安乡县| 牙克石市| 神木县| 棋牌| 安宁市| 洪雅县|