ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS
場景
搭建ElementUI前端項目后提示:
Access to XMLHttpRequest at **from origin ** has been blocked by CORS policy
?
這是因為在請求后臺SpringBoot接口時出現(xiàn)了跨域請求問題。
本來打算是搭建好前端項目后再js中進(jìn)行ajaxq請求數(shù)據(jù),但是會因為跨域被拒絕。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關(guān)注公眾號
霸道的程序猿
獲取編程相關(guān)電子書、教程推送與免費下載。
實現(xiàn)
所以使用axios進(jìn)行后臺數(shù)據(jù)的請求
安裝axios
npm install axios?
然后打開入口程序main.js添加axios
import axios from 'axios'?
然后打開webpack.config.js進(jìn)行url的代理配置
?
devServer: {host: '127.0.0.1',port: 8010,proxy: {'/api/': {target: 'http://127.0.0.1:8088',changeOrigin: true,pathRewrite: {'^/api': ''}}},?
以上配置代表項目的啟動端口為8010,ElementUI在向后臺請求Url時,就會將/api/的請求想target中執(zhí)行的地址去請求
所以我們可以在頁面App.vue中這樣去調(diào)用后臺數(shù)據(jù)接口
//頁面初始化的時候,去調(diào)用created: function(){debuggerthis.getData()},methods: {//通過ajax去請求服務(wù)端,獲取數(shù)據(jù)getData() {debuggerlet url = "/api/user/selectAllLimit?offset=2&limit=1" ;this.$axios.get(url).then((res) => {this.tableData = res.data;//把傳回來數(shù)據(jù)賦給packData}).catch(function(error){console.log(error);})}請求效果
?
總結(jié)
以上是生活随笔為你收集整理的ElementUI项目请求SpringBoot后台项目时提示:Access to XMLHttpRequest at **from origin ** has been blocked by CORS的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 怎样使用element-starter快
- 下一篇: SpringBoot+MyBatisPl