SpringBoot服務(wù)器端解決跨域問(wèn)題
本文導(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ò)誤如下:
所以說(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)文章!
相關(guān)文章:
1. java實(shí)現(xiàn)圖形化界面計(jì)算器2. IntelliJ Idea2017如何修改緩存文件的路徑3. IntelliJ IDEA設(shè)置條件斷點(diǎn)的方法步驟4. IIS Express 取代 ASP.NET Development Server的配置方法5. python flask框架快速入門6. Spring-Richclient 0.1.0 發(fā)布7. javascript設(shè)計(jì)模式 ? 建造者模式原理與應(yīng)用實(shí)例分析8. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式9. Python使用oslo.vmware管理ESXI虛擬機(jī)的示例參考10. Express 框架中使用 EJS 模板引擎并結(jié)合 silly-datetime 庫(kù)進(jìn)行日期格式化的實(shí)現(xiàn)方法
