Vue 使用Axios 跨域問題

在Vue 項目學習的過程中遇到了,Axios跨域的問題。
有很多這方面的解決博文,但大多都是 vue 3以前的並不適合。
也有Vue3的,但都太難懂了不夠直接、

vue安裝 axios

npm install axios   

接着在項目中添加 vue.config.js 配置文件
在這裏插入圖片描述
vue.config.js
我這裏以百度音樂的接口爲示例

module.exports = {
    devServer: {
        proxy: {
            '/music': {
                target: 'http://tingapi.ting.baidu.com',        // 目標主機      
                ws: true,
                changeOrigin: true,
                pathRewrite:{
                    '^/music': ''
                }
            }
        } 
    }
}

摘選自 官方 CLI 配置文檔的記錄
CLI 配置連接
在這裏插入圖片描述

接着我們在組件中使用 axios 進行測試

App.vue

<template>
  <div id="app">
    <p> {{ message }} </p>
    <button @click="buttonAxios"> {{buttonText}} </button>
  </div>
</template>

<script>

import Axios from 'axios'       // 導入 axios庫

export default {
  name: 'App',
  data:function(){
    return {
      message:'hello word',
      buttonText:'Click Me'
    }
  },
  methods:{
    buttonAxios:function(){

      // 獲取百度音樂列表
      Axios.get('music/v1/restserver/ting', {
        params:{
          method: 'baidu.ting.billboard.billList',
          type: 1,
          size: 10,
          offset: 0
        }
      }).then(musicResult => {
        console.dir(musicResult);
      }).catch(musicError => {
        console.dir(musicError);
      });
      
    }
  }
}
</script>

<style>

</style>

當然如果你不想污染全局環境的話,可以這樣做,將它掛載到原型上。

CookBook連接

在這裏插入圖片描述
在控制檯輸入

npm run serve

運行WebServe 服務器,然後點擊 按鈕,查看控制檯,效果大致如下。
在這裏插入圖片描述

遺憾的是,這種做法只能在 WebServer 行的通。
如果你,使用

npm run build

來編譯成html文件來使用,是不行的。
會出現這種情況,所以你如果是使用build出來用的話,或者可以考慮jQuery。
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章