如何在Vue3項目中利用axios實現跨域?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
實現跨域共3個步驟:
1,vue3.0根目錄下創建vue.config.js文件;
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'https://you.163.com/', //接口域名
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
secure: true, //是否https接口
pathRewrite: { //路徑重置
'^/api': ''
}
}
}
}
};2,將上述代碼塊寫入其中;
如圖:

3,將api接口放入請求的url中;
使用頁面的代碼塊:
<template>
<div>
<H1>TEST</H1>
<p>{{data}}</p>
</div>
</template>
<script>
import axis from 'axios';
export default {
name: 'Test',
data() {
return {
data: {},
};
},
methods: {
getData() {
axis.get('/api/xhr/search/queryHotKeyWord.json')//axis后面的.get可以省略;
.then(
(response) => {
console.log(response);
this.data = response;
})
.catch(
(error) => {
console.log(error);
});
},
},
mounted() {
this.getData();
},
};
</script>
<style scoped>
</style>代碼解析:

瀏覽器頁面:

剩下的就是把數據渲染到頁面了。
實際示例
vue3 8080端口請求flask8081端口服務數據:
module.exports = {
devServer: {
host: '0.0.0.0',
port: 8080,
open: true,
proxy: {
'/api/testcase/': {
target: 'http://127.0.0.1:8081/', //接口域名
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
secure: true, //是否https接口
pathRewrite: { //路徑重置
'^/api/testcase/': '/api/testcase/'
}
}
},
},
}flask接口地址:
# http://127.0.0.1:8081/api/testcase/@app.route('/api/testcase/')def alltestcase(): pass
看完上述內容,你們掌握如何在Vue3項目中利用axios實現跨域的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。