詳解axios 全攻略之基本介紹與使用(GET 與 POST)
axios
axios 是一個基于 Promise 的 HTTP 客戶端,專門為瀏覽器和 node.js 服務(wù)
Vue 2.0 官方推薦使用 axios 來代替原來的 Vue request,所以這里介紹一下 axios 的功能和基本的使用方法,希望能夠?qū)Ω魑凰袔椭_^
功能
- 在瀏覽器中發(fā)送 XMLHttpRequests 請求
- 在 node.js 中發(fā)送 http 請求
- 支持 Promise API
- 攔截請求和響應(yīng)
- 轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
- 取消請求
- 自動轉(zhuǎn)換 JSON 數(shù)據(jù)格式
- 客戶端支持防范 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); });
同時發(fā)送多個請求
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 }));
當(dāng)然,axios 的功能還包括 axios API、interceptor 等等,這里想要詳細(xì)了解的可以查看官方文檔:axios,后面陸續(xù)會介紹下 interceptor 的使用和各類參數(shù)的配置。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
vue el-table字段點擊出現(xiàn)el-input輸入框,失焦保存方式
這篇文章主要介紹了vue el-table字段點擊出現(xiàn)el-input輸入框,失焦保存方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02vue實現(xiàn)盒子內(nèi)拖動方塊移動的示例代碼
這篇文章主要給大家介紹了如何通過vue實現(xiàn)盒子內(nèi)拖動方塊移動,文章通過代碼示例講解的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴可以參考閱讀本文2023-08-08Vue3?Radio單選切換展示不同內(nèi)容實現(xiàn)代碼
這篇文章主要介紹了Vue3?Radio單選切換展示不同內(nèi)容,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07Electron?store及shareObject進(jìn)程間數(shù)據(jù)交互存儲功能封裝
這篇文章主要為大家介紹了Electron?store及shareObject進(jìn)程間數(shù)據(jù)交互存儲功能封裝示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09