vue-cli3 axios解決跨域問題


這種錯誤就是跨域問題:

 

我百度了各種方法,最終下面這種方法解決了,直接上代碼: 

解決:

如果沒安裝axios:  

npm install axios -save     //安裝axios

main.js

 //引入axios
import axios from 'axios'
Vue.prototype.axios=axios

axios.defaults.baseURL = '/api'

 

我用的是vue-cli3開發的項目,沒有vue.config.js目錄,這個是我新建的

 

 vue.config.js中的代碼:

module.exports = {
    devServer: {
        proxy: {
            '/api': {
                // 此處的寫法,我訪問的是http://localhost:8080/api/dataHome.json設置代理后,axios請求不需要把域名帶上,只需要把路徑前面加上 /api 即可。
                target: 'http://localhost:8080/api/',
                // 允許跨域
                changeOrigin: true,
                ws: true,
                pathRewrite: {
                    '^/api': ''
                }
            }
        }
    }
}

請求路徑:

由於設置了 pathRewrite,所以請求時會把 /api 替換成 '',最終的請求路徑為 /dataHome.json
methods:{
            http(){
                let that=this;
                this.axios.get("/dataHome.json")
                .then((res)=>{
                    console.log(res);
                }).catch((error)=>{
                    console.log(error)
                })
            }
        }

重新運行

npm run serve

最后請求到了數據,嘿嘿

 


免責聲明!

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



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