久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

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

本文導航

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(' * '),表示接收所有來源的請求。

注意點:

1、路徑來源的寫法問題

如果后臺指定路徑來源為:http://localhost:8081

那么在瀏覽器里訪問前端頁面的時候,必須用 http://localhost:8081,不可以寫成127.0.0.1或者本機ip地址。否則還是會報跨域錯誤。測試如下

后臺設(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>

啟動服務(wù),瀏覽器里訪問:

http://localhost:8081/index.html

正常返回結(jié)果

瀏覽器里訪問:

http://127.0.0.1:8081/index.html

報跨域錯誤如下:

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

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

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

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); } }) }

經(jīng)過測試,是可以的,只要瀏覽器里訪問頁面的路徑寫法與后臺保持一致就可以了。

2、攜帶Cookie

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

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

標簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 勐海县| 天峨县| 聂拉木县| 商水县| 辽阳县| 鹤壁市| 云安县| 文昌市| 重庆市| 那坡县| 永吉县| 陈巴尔虎旗| 长寿区| 奉贤区| 馆陶县| 楚雄市| 津南区| 绵阳市| 鹰潭市| 惠来县| 新津县| 若尔盖县| 江孜县| 舟山市| 罗定市| 县级市| 牙克石市| 方山县| 会同县| 犍为县| 石门县| 淮南市| 保德县| 玛多县| 蒙山县| 镶黄旗| 仁寿县| 运城市| 连州市| 河西区| 修武县|