Axios 是一個(gè)基于 promise 的 HTTP 庫(kù),可以用在瀏覽器和 node.js 中。
- 從瀏覽器中創(chuàng)建 XMLHttpRequests
- 從 node.js 創(chuàng)建 http 請(qǐng)求
- 支持 Promise API
- 攔截請(qǐng)求和響應(yīng)
- 轉(zhuǎn)換請(qǐng)求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
- 取消請(qǐng)求
- 自動(dòng)轉(zhuǎn)換 JSON 數(shù)據(jù)
- 客戶端支持防御 XSRF
安裝
使用npm安裝
npm install axios
使用 bower安裝
bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
例子:
vue中全局使用
1.結(jié)合 vue-axios使用
看了vue-axios的源碼,它是按照vue插件的方式去寫的。那么結(jié)合vue-axios,就可以去使用vue.use方法了
首先在主入口文件main.js中引用:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios,axios);
之后就可以使用了,在組件文件中的methods里去使用了:
getNewsList(){
this.axios.get('api/getNewsList').then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
}
2.axios 改寫為 Vue 的原型屬性
首先在主入口文件main.js中引用,之后掛在vue的原型鏈上:
import axios from 'axios'
Vue.prototype.$ajax= axios
在組件中使用:
this.$ajax.get('api/getNewsList')
.then((response)=>{
this.newsList=response.data.data;
}).catch((response)=>{
console.log(response);
})
局部使用
直接引入
import axios from 'axios'
然后就可以直接用了
常用的配置項(xiàng)初始化
// 常規(guī)配置項(xiàng)
axios.defaults.baseURL = 'https://127.0.0.1:9999'; // 請(qǐng)求服務(wù)器具體的地址
axios.defaults.withCredentials =true; // 在跨域中允許攜帶憑證
axios.defaults.header['Content-Type'] = 'application/x-www-form-urlencoded';// 聲明傳給服務(wù)器的數(shù)據(jù),通過(guò)請(qǐng)求傳給服務(wù)器的數(shù)據(jù)application/x-www-form-urlencoded格式
axios.defaults.headers.common["token"] = token; // 攜帶token請(qǐng)求頭
// 請(qǐng)求攔截器:當(dāng)我們通過(guò)porps請(qǐng)求向服務(wù)器發(fā)請(qǐng)求的時(shí)候,能攔截到請(qǐng)求主體信息,然后把請(qǐng)求主體傳遞進(jìn)來(lái)的json格式的對(duì)象,變成urlencoded 某某某等于&某某某格式發(fā)送給服務(wù)器
axios.defaults.transformRequest = function (data) {
if (data) return data;
let result = ``;
for (let attr in data) {2
if(!data.hasOwnProperty(attr)) break;
result += `&${attr}=${data[attr]}`;
}
return result.substring(1);
};
// 響應(yīng)服務(wù)器:接受服務(wù)器返回的結(jié)果,把返回的結(jié)果,因?yàn)樗腶nshuosi從服務(wù)器獲得的結(jié)果response對(duì)象當(dāng)中包含了很多信息,既有響應(yīng)頭也有相應(yīng)主體的信息,xx配置信息。
// 現(xiàn)在只拿到data,如果有錯(cuò)誤就拋出錯(cuò)誤的Promise,
axios.interceptor.response.use(function onFultfilled(response) {
// 成功走這個(gè)
return response.data;
}, function onRejected(reason) {
// 失敗走這個(gè)
return Promise.reject(reason);
});
// 驗(yàn)證什么時(shí)候成功失敗,用正則檢驗(yàn),自定義成功失敗,主要以http狀態(tài)碼
axios.dafaults.validateStatus = function (status) {
// http狀態(tài)碼,2或者3開頭的都是成功,默認(rèn)只有2開頭的才能成功
return /^(2\3)\d{2}$/.test(status);
}
使用方式示例
1.執(zhí)行g(shù)et數(shù)據(jù)請(qǐng)求
axios.get('url',{
params:{
id:'接口配置參數(shù)(相當(dāng)于url?id=xxxx)',
},
})
.then((res)=>{
console.log(res); // 處理成功的函數(shù) 相當(dāng)于success
})
.catch((error)=>{
console.log(error) // 錯(cuò)誤處理 相當(dāng)于error
})
2.執(zhí)行post數(shù)據(jù)發(fā)送
const data = {
name:'張三',
age:23
}
axios.post('url',data)
.then((res)=>{
console.log(res); // 處理成功的函數(shù) 相當(dāng)于success
})
.catch((error)=>{
console.log(error) // 錯(cuò)誤處理 相當(dāng)于error
})
3.執(zhí)行delete 數(shù)據(jù)發(fā)送
// 如果服務(wù)端將參數(shù)作為java對(duì)象來(lái)封裝接受
axios.delete('demo/url', {
data: {
id: 123,
name: 'Henry',
},
timeout: 1000,
})
// 如果服務(wù)端將參數(shù)作為url參數(shù)來(lái)接受,則請(qǐng)求的url為:www.demo/url?a=1&b=2形式
axios.delete('demo/url', {
params: {
id: 123,
name: 'Henry',
},
timeout: 1000
})
4.執(zhí)行put 數(shù)據(jù)發(fā)送
axios.put('demo/url', {
id: 123,
name: 'Henry',
sex: 1,
phone: 13333333
})
5.攜帶請(qǐng)求頭
axios設(shè)置請(qǐng)求頭中的Authorization信息:
GET請(qǐng)求
this.$axios.get('/url',
{
headers: {
'Authorization': 'Bearer '+localStorage.getItem('token'),
'token': ' '
...
},
params: {
param1: string,
param2: string
},
...
}
)
.then(res => fn)
.catch(err => fn)
POST請(qǐng)求
this.$axios.post('/url', param,
{
headers: {
'Authorization': 'Bearer '+localStorage.getItem('token'),
'token': ' '
...
}
...
}
)
.then(res => fn)
.catch(err => fn)