­

Vue中跨域問題解決方案1

  • 2020 年 5 月 16 日
  • 筆記

我們需要配置代理。代理可以解決的原因:因為客戶端請求服務端的數據是存在跨域問題的,而服務器和服務器之間可以相互請求數據,是沒有跨域的概念(如果服務器沒有設置禁止跨域的權限問題),也就是說,我們可以配置一個代理的服務器可以請求另一個服務器中的數據,然後把請求出來的數據返回到我們的代理服務器中,代理服務器再返回數據給我們的客戶端,這樣我們就可以實現跨域訪問數據。

報錯如下:

 

 解決方案如下:

1. 在項目根目錄新建vue.config.js文件

2. 配置代理

module.exports = {
  devServer: {
    proxy: {
      '/api': {
        target: '//localhost:4000', //對應自己的接口
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
}

3. 在main.js文件,配置一下axios.defaults.baseURL = ‘/api’ 這樣就可以保證動態的匹配生產和開發環境的定義前綴了,代碼如下:

/*
入口JS
*/
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //關鍵代碼
Vue.config.productionTip = false

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

4. 在組件中使用axios請求數據

<template>
 
</template>

<script>
    import FooterGuide from './components/FooterGuide/FooterGuide.vue'
    export default {
        created() {
            const url = '/index_category'
            this.$axios.get(url).then(res => {
                console.log(res)
            })
        },
    }
</script>

<style lang="stylus" rel="stylesheet/stylus">

</style>

5. 重新啟動項目之後,已經解決了跨域問題。切記…