溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何在Vue3項目中利用axios實現(xiàn)跨域

發(fā)布時間:2020-11-25 14:40:59 來源:億速云 閱讀:2540 作者:Leah 欄目:開發(fā)技術

如何在Vue3項目中利用axios實現(xiàn)跨域?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

實現(xiàn)跨域共3個步驟:

1,vue3.0根目錄下創(chuàng)建vue.config.js文件;

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: 'https://you.163.com/', //接口域名
        changeOrigin: true,       //是否跨域
        ws: true,            //是否代理 websockets
        secure: true,          //是否https接口
        pathRewrite: {         //路徑重置
          '^/api': ''
        }
      }
    }
  }
};

2,將上述代碼塊寫入其中;

如圖:

如何在Vue3項目中利用axios實現(xiàn)跨域

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項目中利用axios實現(xiàn)跨域

瀏覽器頁面:

如何在Vue3項目中利用axios實現(xiàn)跨域

剩下的就是把數(shù)據(jù)渲染到頁面了。

實際示例

vue3 8080端口請求flask8081端口服務數(shù)據(jù):

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實現(xiàn)跨域的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI