axios
基于http客戶端的promise,面向?yàn)g覽器和nodejs
特色
•瀏覽器端發(fā)起XMLHttpRequests請求
•node端發(fā)起http請求
•支持Promise API
•監(jiān)聽請求和返回
•轉(zhuǎn)化請求和返回
•取消請求
•自動轉(zhuǎn)化json數(shù)據(jù)
•客戶端支持抵御
安裝
使用npm:
$ npm i axiso
為了解決post默認(rèn)使用的是x-www-from-urlencoded 去請求數(shù)據(jù),導(dǎo)致請求參數(shù)無法傳遞到后臺,所以還需要安裝一個插件QS
$ npm install qs
一個命令全部解決
$ npm install --save axios vue-axios qs
兩種方法在vue中使用 axios
方法-:修改原型鏈
首先在 main.js 中引入 axios
import Axiso from 'axiso'
這時候如果在其它的組件中,是無法使用 axios 命令的。但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題
Vue.prototype.$axios= Axios
配置好了之后就可以全局使用了
示例:在main.js使用
Get請求:
//發(fā)起一個user請求,參數(shù)為給定的ID$axios.get('/user?ID=1234').then(function(respone){ console.log(response);}).catch(function(error){ console.log(error);});Post請求
$axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });為了保證請求的數(shù)據(jù)正確,可以在main.js配置如下內(nèi)容:
Axios.defaults.baseURL = 'https://api.example.com';//配置你的接口請求地址Axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;//配置token,看情況使用Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//配置請求頭信息。
那么最基本的配置已經(jīng)完成了,但是還有一個問題,既然是前后端分離,那么肯定避免不了跨域請求數(shù)據(jù)的問題,接下來就是配置跨域了。
在config/index.js里面的dev里面配置如下代碼:
proxyTable: { '/api': { target: 'http://xxx.xxx.xxx.xxx:8081/',//設(shè)置你調(diào)用的接口域名和端口號 別忘了加http changeOrigin: true, pathRewrite: { '^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我要調(diào)用'http://xxx.xxx.xxx.xx:8081/user/add',直接寫‘/api/user/add'即可 } }完整代碼:
dev: { // Paths assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: { '/api': { target: 'http://xxx.xxx.xxx.xxx:8081/',//設(shè)置你調(diào)用的接口域名和端口號 別忘了加http changeOrigin: true, pathRewrite: { '^/api': '/'//這里理解成用‘/api'代替target里面的地址,后面組件中我們掉接口時直接用api代替 比如我 要調(diào)用'http://xxx.xxx.xxx.xxx:8081/user/add',直接寫‘/api/user/add'即可 } } },
新聞熱點(diǎn)
疑難解答
圖片精選