Vue筆記: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/'
                }
            }
        },
    },
}
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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM