axios 全攻略之基本介紹與使用(GET 與 POST)
阿新 • • 發佈:2018-05-23
pkg 需要 name comm xmlhttp 基本介紹 markdown pre spa
axios
axios 是一個基於 Promise 的 HTTP 客戶端,專門為瀏覽器和 node.js 服務
Vue 2.0 官方推薦使用 axios 來代替原來的 Vue request,所以這裏介紹一下 axios 的功能和基本的使用方法,希望能夠對各位所有幫助。^_^
功能
- 在瀏覽器中發送 XMLHttpRequests 請求
- 在 node.js 中發送 http 請求
- 支持 Promise API
- 攔截請求和響應
- 轉換請求和響應數據
- 取消請求
- 自動轉換 JSON 數據格式
- 客戶端支持防範 XSRF 攻擊
瀏覽器支持
axios 能夠支持 IE7 以上的 IE 版本,同時能夠支持大部分主流的瀏覽器,需要註意的是,你的瀏覽器需要支持 Promise,才能夠使用 axios。所以比較好的做法是先安裝 polyfill,然後再使用 axios。
安裝
Using npm:
$ npm install axios
Using bower:
$ bower install axios
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
使用
這裏以 Vue 為例:在 NPM 中安裝 axios 之後,需要在 main.js 文件中引用 package
import axios from ‘axios‘
然後全局綁定
Vue.prototype.$http = axios
然後可以在 .vue 文件中使用 $http
來代替 axios
GET
// Make a request for a user with a given ID
axios.get(‘/user?ID=12345‘)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get(‘/user‘, {
params: {
ID: 12345
}
})
.then(function (response) {
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);
});
同時發送多個請求
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) {
// Both requests are now complete
}));
當然,axios 的功能還包括 axios API、interceptor 等等,這裏想要詳細了解的可以查看官方文檔:axios,後面陸續會介紹下 interceptor 的使用和各類參數的配置。
版權聲明:本作品采用知識共享署名-非商業性使用-禁止演繹 3.0 未本地化版本許可協議進行許可。 https://blog.csdn.net/xjlinme/article/details/77650059axios 全攻略之基本介紹與使用(GET 與 POST)