實現跨域共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/' } } }, }, }
axis.get('/api/testcase/')//axis后面的.get可以省略;
.then(
(response) => {
console.log(response);
this.totaltableData = response.data['result'];
})
.catch(
(error) => {
console.log(error);
});
flask接口地址:
# http://127.0.0.1:8081/api/testcase/ @app.route('/api/testcase/') def alltestcase(): pass
參考:https://blog.csdn.net/weixin_45264991/article/details/104182742
