Vue封裝axios的示例講解
1、axios:是一個基于Promise的網絡請求庫。既可以在node.js(服務器端)使用,也可以在瀏覽器端使用
(1)在node.js中使用的原生的http模塊
(2)在瀏覽器中使用的XMLHttpRequest
2、vue中的使用方法
(1)安裝:npm install axios
(2)引用方法:
原生的方式(不推薦使用)
axios({ url:'http://127.0.0.1:9001/students/test', //遠程服務器的url method:'get', //請求方式 }).then(res=>{ this.students = res.data }).catch(e=>{ console.error(e); }) //缺點:每個使用axios的組件都需要導入
注:axios對服務端數據的封裝
- res.config:響應信息的配置情況
- res.data:響應的數據
- res.headers:響應頭信息(信息的大小、信息的類型)
- res.request:請求對象
- res.status:請求、響應的狀態(tài)碼
- res.statusText:請求、響應狀態(tài)碼對應的文本信息
在項目的main.js文件中導入axios,將其寫入Vue的原型中(推薦使用)
import axios from "axios"; Vue.prototype.$http = axios
在組件中通過this.$http的方式使用
this.$http.get('http://127.0.0.1:9001/students/test').then(res=>{ this.students = res.data }).catch(e=>{ console.log(e) })
缺點:只能在vue2使用,vue3中不能用
將axios單獨封裝到某個配置文件中(在配置文件中單獨封裝axios實例)
(1)配置文件:axiosApi.js
import axios from "axios"; const axiosApi = axios.create({ baseURL:'http://127.0.0.1:9001', //基礎地址 timeout:2000 //連接超時的時間(單位:毫秒) }) export default axiosApi //axiosApi是axios的實例
(2)使用:
import $http from '../config/axiosapi' $http.get('/students/test').then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
優(yōu)點:既可以在vue2中使用,也可以在vue3中使用
3、axios的不同請求方式向服務器提交數據的格式:
(1)get請求:服務器端通過req.quert參數名來接收
直接將請求參數綁定在url地址上
let str = '張三' $http.get('/students/test/?username='+str).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
通過params方式進行提交
let str = '張三' $http.get('/students/test',{ params:{ username:str } }).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
(2)post方式請求:服務器端通過req.body.參數名獲取數據
let str = '張三' $http.post('/students/test',{ username:str }).then(res=>{ this.students = res.data.info }).catch(e=>{ console.log(e) })
(3)put方式請求:和post方式一樣
(4)delete方式請求:和get方式一樣
到此這篇關于Vue封裝axios的示例講解的文章就介紹到這了,更多相關Vue axios內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Vue全局共享數據之globalData,vuex,本地存儲的使用
這篇文章主要介紹了Vue全局共享數據之globalData,vuex,本地存儲的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10