1.安裝
npm install axios
或者 使用 bower:
bower install axios
或者直接使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
2.引入axios
import axios from 'axios'
這時候如果在其它的組件中,是無法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題
Vue.prototype.axios = axios
通過 this.axios({})來訪問
3.基本使用
axios({ url:'http://localhost/api/aaa', method:'POST', headers:{ Authorization:'Bearer eyJ0eXAiABUg-Fxs...', Accept:'application/json' } }).then(res=>{ console.log(res,'res') }).catch(res1=>{ console.log(res1,'res1') })
然后報CORS錯誤
Access to XMLHttpRequest at 'http://backend.com/api/aaa' from origin 'http://localhost:8085' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
根據提示可以看出是跨越了
跨越的三個條件:協議、域名、端口號
這個請求明顯端口號不一致,找到問題了,那就好說了
4.axios配置 proxyTable
在config/index.js中的proxyTable中添加以下內容:
"/api": { target: "http://backend.com/api", changeOrigin: true, pathRewrite: { '^/api': '' } }
保存,重新運行 npm run dev
5.更改url,重新請求
axios({ url:'/api/aaa', method:'POST', headers:{ Authorization:'Bearer 5llcq3GiwABUg-Fxs...', Accept:'application/json' } }).then(res=>{ console.log(res,'res') }).catch(res1=>{ console.log(res1,'res1') })
請求結果如下,跨越解決了