axios: 是一個(gè)類庫(kù)咐低,基于Promise管理的Ajax庫(kù)搓幌,支持瀏覽器和nodejs的http庫(kù),常用于Ajax請(qǐng)求。
特點(diǎn)
從瀏覽器中創(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>
axios提供了多種請(qǐng)求方式卢未,比如直接發(fā)起get或post請(qǐng)求:
執(zhí)行g(shù)et請(qǐng)求
// 為給定 ID 的 user 創(chuàng)建請(qǐng)求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可選地携取,上面的請(qǐng)求可以這樣做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
在get請(qǐng)求中的鍵值對(duì)拼接成URLENCODED式的字符串然后1以問號(hào)傳遞參數(shù)的方式稚疹,傳遞給服務(wù)器香拉。
執(zhí)行post請(qǐng)求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
基于Promise,可以執(zhí)行多個(gè)并發(fā)請(qǐng)求:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 請(qǐng)求現(xiàn)在都執(zhí)行完成時(shí)
}));
也可以通過寫入配置的形式發(fā)起請(qǐng)求:
axios(config)
// 發(fā)送 POST 請(qǐng)求
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
})
.then(function(res) {
console.log(res)
});
在業(yè)務(wù)中,經(jīng)常將其封裝成為實(shí)例的形式調(diào)用姻氨,便于做通用配置钓辆,
例如:
//util.js
const instance = axios.create({
baseURL: 'http://some-domain.com/api',
timeout: 1000,
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
export default instance
index.js
<tempalte>
<div></div>
</template>
<script>
import Ajax from './util.js'
export default {
created(): {
Ajax ( {
method: 'post',
url: '/user',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then(res => {
console.log(res)
})
}
}
</script>
請(qǐng)求方法的別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
標(biāo)注: 在使用別名方法時(shí), url肴焊、method前联、data 這些屬性都不必在配置中指定。
并發(fā)
處理并發(fā)請(qǐng)求的助手函數(shù)
axios.all(iterable)
axios.spread(callback)
創(chuàng)建實(shí)例
可以使用自定義配置新建一個(gè) axios 實(shí)例
axios.create([config])
var instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
更多關(guān)于axios的配置請(qǐng)參考: https://www.kancloud.cn/yunye/axios/234845