SpringBoot服務(wù)器端解決跨域問(wèn)題
本文導(dǎo)航
SpringBoot解決跨域問(wèn)題的兩種方案:
1、通過(guò)給方法或者類(lèi)加注解的形式,@CrossOrigin。
2、繼承接口,重寫(xiě)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)源,可以寫(xiě)成“*”,表示接收所有來(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也可以寫(xiě)成allowedOrigins(' * '),表示接收所有來(lái)源的請(qǐng)求。
注意點(diǎn):
1、路徑來(lái)源的寫(xiě)法問(wèn)題
如果后臺(tái)指定路徑來(lái)源為:http://localhost:8081
那么在瀏覽器里訪問(wèn)前端頁(yè)面的時(shí)候,必須用 http://localhost:8081,不可以寫(xiě)成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ò)誤如下:
所以說(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è)面的路徑寫(xiě)法與后臺(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)文章!
相關(guān)文章:
1. python如何寫(xiě)個(gè)俄羅斯方塊2. JAVA抽象類(lèi)及接口使用方法解析3. 《CSS3實(shí)戰(zhàn)》筆記--漸變?cè)O(shè)計(jì)(一)4. 如何通過(guò)vscode運(yùn)行調(diào)試javascript代碼5. Python結(jié)合百度語(yǔ)音識(shí)別實(shí)現(xiàn)實(shí)時(shí)翻譯軟件的實(shí)現(xiàn)6. python b站視頻下載的五種版本7. Java構(gòu)建JDBC應(yīng)用程序的實(shí)例操作8. JavaScript設(shè)計(jì)模式之策略模式實(shí)現(xiàn)原理詳解9. XML基本概念XPath、XSLT與XQuery函數(shù)介紹10. vue之elementUi的el-select同時(shí)獲取value和label的三種方式
