vue axios在開發中遇到的問題

第一次學vue,自己摸索了好久。用axios的時候遇到了幾個問題。跨域,還有就是多個proxyTable配置的時候出現的問題。記下,方便以後查閱

var _this=this;
 _this.$axios.get("http://xxxx/js/shopData.json").then(res=>{
       console.log(res.data)
})

這樣寫乍一看是沒有問題的,但是瀏覽器拋出了一個錯誤

No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

什麼意思呢?就是跨域了,那麼應該怎麼來解決這個跨域的問題?

1.首先在main.js配置如下代碼

Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/api'
Axios.defaults.headers.post['Content-Type'] = 'application/json';

2.其次在index.js 中的proxyTable配置如下代碼

 proxyTable: {
      '/api':{
        target: "http://xxxx/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/api':''
        }
      }
    },

然後把axios改成

var _this=this;
 _this.$axios.get("/js/shopData.json").then(res=>{
       console.log(res.data)
})

假設接口服務器在 https://xxxx,本地服務器是 http://localhost:8080

原接口 https://xxxx/js/shopData.json 代理到 http://localhost:8080/api/js/shopData.json
撒花,跨域成功~~~

如果我們有多個接口呢?webpack devserver proxy 如何匹配代理多個路徑到不同host?

1.首先在index.js 中的proxyTable配置

    proxyTable: {
      '/api':{
        target: "http://xxxx/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/api':''
        }
      },  
      '/test':{
        target: "https://yyy/",
        secure: false,
        changeOrigin:true,
        pathRewrite:{
            '^/test':''
        },
      }  
    },

2.然後請求第二個接口就可以了,第二個接口爲 https://yyy/order.php

var _this=this;
 _this.$axios.get("/test/order.php").then(res=>{
       console.log(res.data)
})

問題來了,報錯
http://localhost:8080/api/test/order.php 403 (Forbidden)
找不到這個東西,爲啥有帶了api,難道自動匹配到第一個接口,在第一個接口找不到php這個文件才報錯??
細想了一下會不會axios的配置默認帶了api回頭一看

3.更改axios的配置

Vue.prototype.$axios = Axios
Axios.defaults.baseURL = '/'
Axios.defaults.headers.post['Content-Type'] = 'application/json';

然後第一個接口url自己帶上api就可以訪問了/api/js/shopData.json

這個是我在開發中遇到的問題,希望能夠幫助到你

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