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

您的位置:首頁技術文章
文章詳情頁

SpringBoot服務器端解決跨域問題

瀏覽:92日期: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地址。否則還是會報跨域錯誤。測試如下

后臺設置:

@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

報跨域錯誤如下:

SpringBoot服務器端解決跨域問題

所以說,瀏覽器訪問路徑需要與后臺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地址,否則也會報錯。

以上就是SpringBoot服務器端解決跨域問題的詳細內容,更多關于SpringBoot 解決跨域的資料請關注好吧啦網其它相關文章!

標簽: Spring
相關文章:
主站蜘蛛池模板: 外汇| 军事| 呼伦贝尔市| 宁海县| 阳城县| 中牟县| 廉江市| 类乌齐县| 泽州县| 福安市| 宣汉县| 汝州市| 昌吉市| 基隆市| 伊金霍洛旗| 南宫市| 旬邑县| 昂仁县| 周宁县| 琼结县| 南京市| 佛学| 清远市| 庄浪县| 乡城县| 濮阳县| 宜兰县| 寿宁县| 彩票| 临邑县| 常德市| 石景山区| 翁牛特旗| 德安县| 盐山县| 惠安县| 泗水县| 临潭县| 浦县| 广安市| 四会市|