前端(vue)入門到精通課程:進(jìn)入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點(diǎn)擊使用
提示:本篇詳解axios在vue項(xiàng)目中的實(shí)例。在使用Vue.js框架開發(fā)前端項(xiàng)目時(shí),會(huì)經(jīng)常發(fā)送ajax請求服務(wù)端接口,在開發(fā)過程中,需要對axios進(jìn)一步封裝,方便在項(xiàng)目中的使用。【學(xué)習(xí)視頻分享:vue視頻教程、web前端視頻】
Axios簡介
axios框架全稱(ajax – I/O – system):
- 基于
promise
用于瀏覽器和node.js
的http客戶端,因此可以使用Promise API
一、axios是干啥的
說到axios
我們就不得不說下Ajax
。在舊瀏覽器頁面在向服務(wù)器請求數(shù)據(jù)時(shí),因?yàn)榉祷氐氖钦麄€(gè)頁面的數(shù)據(jù),頁面都會(huì)強(qiáng)制刷新一下,這對于用戶來講并不是很友好。并且我們只是需要修改頁面的部分?jǐn)?shù)據(jù),但是從服務(wù)器端發(fā)送的卻是整個(gè)頁面的數(shù)據(jù),十分消耗網(wǎng)絡(luò)資源。而我們只是需要修改頁面的部分?jǐn)?shù)據(jù),也希望不刷新頁面,因此異步網(wǎng)絡(luò)請求就應(yīng)運(yùn)而生。
Ajax(Asynchronous JavaScript and XML):
異步網(wǎng)絡(luò)請求。Ajax能夠讓頁面無刷新的請求數(shù)據(jù)。
實(shí)現(xiàn)ajax的方式有多種,如jQuery封裝的ajax,原生的XMLHttpRequest,以及axios。但各種方式都有利弊:
- 原生的XMLHttpRequest的配置和調(diào)用方式都很繁瑣,實(shí)現(xiàn)異步請求十分麻煩
- jQuery的ajax相對于原生的ajax是非常好用的,但是沒有必要因?yàn)橐胊jax異步網(wǎng)絡(luò)請求而引用jQuery框架
Axios(ajax i/o system):
這不是一種新技術(shù),本質(zhì)上還是對原生XMLHttpRequest的封裝,可用于瀏覽器和nodejs的HTTP客戶端,只不過它是基于Promise的,符合最新的ES規(guī)范。具備以下特點(diǎn):
- 在瀏覽器中創(chuàng)建XMLHttpRequest請求
- 在node.js中發(fā)送http請求
- 支持Promise API
- 攔截請求和響應(yīng)
- 轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
- 取消要求
- 自動(dòng)轉(zhuǎn)換JSON數(shù)據(jù)
-
客戶端支持防止CSRF/XSRF(跨域請求偽造)
二、安裝使用
安裝有三種方式:
npm安裝
npm install axios
bower安裝
bower install axios
通過cdn引入
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
在vue項(xiàng)目的main.js
文件中引入axios
import axios from 'axios' Vue.prototype.$axios = axios
在組件中使用axios
<script> export default { mounted(){ this.$axios.get('/goods.json').then(res=>{ console.log(res.data); }) } } </script>
三、Axios請求方式
- get:獲取數(shù)據(jù),請求指定的信息,返回實(shí)體對象
- post:向指定資源提交數(shù)據(jù)(例如表單提交或文件上傳)
- put:更新數(shù)據(jù),從客戶端向服務(wù)器傳送的數(shù)據(jù)取代指定的文檔的內(nèi)容
- patch:更新數(shù)據(jù),是對put方法的補(bǔ)充,用來對已知資源進(jìn)行局部更新
- delete:請求服務(wù)器刪除指定的數(shù)據(jù)
示例代碼
方法一
//請求格式類似于 http://localhost:8080/goods.json?id=1 this.$axios.get('/goods.json',{ params: { id:1 } }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
方法二
this.$axios({ method: 'get', url: '/goods.json', params: { id:1 } }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
post請求一般分為兩種類型
1、form-data
表單提交,圖片上傳、文件上傳時(shí)用該類型比較多
2、application/json
一般是用于 ajax 異步請求
示例代碼
方法一
this.$axios.post('/url',{ id:1 }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
方法二
$axios({ method: 'post', url: '/url', data: { id:1 } }).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
form-data請求
let data = { //請求參數(shù) } let formdata = new FormData(); for(let key in data){ formdata.append(key,data[key]); } this.$axios.post('/goods.json',formdata).then(res=>{ console.log(res.data); },err=>{ console.log(err); })
示例代碼
put請求
this.$axios.put('/url',{ id:1 }).then(res=>{ console.log(res.data); })
patch請求
this.$axios.patch('/url',{ id:1 }).then(res=>{ console.log(res.data); })
示例代碼
參數(shù)以明文形式提交
this.$axios.delete('/url',{ params: { id:1 } }).then(res=>{ console.log(res.data); })
參數(shù)以封裝對象的形式提交
this.$axios.delete('/url',{ data: { id:1 } }).then(res=>{ console.log(res.data); }) //方法二 axios({ method: 'delete', url: '/url', params: { id:1 }, //以明文方式提交參數(shù) data: { id:1 } //以封裝對象方式提交參數(shù) }).then(res=>{ console.log(res.data); })
并發(fā)請求:同時(shí)進(jìn)行多個(gè)請求,并統(tǒng)一處理返回值
示例代碼
this.$axios.all([ this.$axios.get('/goods.json'), this.$axios.get('/classify.json') ]).then( this.$axios.spread((goodsRes,classifyRes)=>{ console.log(goodsRes.data); console.log(classifyRes.data); }) )
四、Axios實(shí)例
示例代碼
let instance = this.$axios.create({ baseURL: 'http://localhost:9090', timeout: 2000 }) instance.get('/goods.json').then(res=>{ console.log(res.data); })
可以同時(shí)創(chuàng)建多個(gè)axios實(shí)例。
axios實(shí)例常用配置:
- baseURL 請求的域名,基本地址,類型:String
- timeout 請求超時(shí)時(shí)長,單位ms,類型:Number
- url 請求路徑,類型:String
- method 請求方法,類型:String
- headers 設(shè)置請求頭,類型:Object
- params 請求參數(shù),將參數(shù)拼接在URL上,類型:Object
- data 請求參數(shù),將參數(shù)放到請求體中,類型:Object
示例代碼
//配置全局的超時(shí)時(shí)長 this.$axios.defaults.timeout = 2000; //配置全局的基本URL this.$axios.defaults.baseURL = 'http://localhost:8080';
示例代碼
let instance = this.$axios.create(); instance.defaults.timeout = 3000;
示例代碼
this.$axios.get('/goods.json',{ timeout: 3000 }).then()
以上配置的優(yōu)先級(jí)為:請求配置 > 實(shí)例配置 > 全局配置
五、攔截器
攔截器:在請求或響應(yīng)被處理前攔截它們
示例代碼
this.$axios.interceptors.request.use(config=>{ // 發(fā)生請求前的處理 return config },err=>{ // 請求錯(cuò)誤處理 return Promise.reject(err); }) //或者用axios實(shí)例創(chuàng)建攔截器 let instance = $axios.create(); instance.interceptors.request.use(config=>{ return config })
示例代碼
this.$axios.interceptors.response.use(res=>{ //請求成功對響應(yīng)數(shù)據(jù)做處理 return res //該返回對象會(huì)傳到請求方法的響應(yīng)對象中 },err=>{ // 響應(yīng)錯(cuò)誤處理 return Promise.reject(err); })
示例代碼
let instance = this.$axios.interceptors.request.use(config=>{ config.headers = { token: '' } return config }) //取消攔截 this.$axios.interceptors.request.eject(instance);
六、錯(cuò)誤處理
示例代碼
this.$axios.get('/url').then(res={ }).catch(err=>{ //請求攔截器和響應(yīng)攔截器拋出錯(cuò)誤時(shí),返回的err對象會(huì)傳給當(dāng)前函數(shù)的err對象 console.log(err); })
七、取消請求
示例代碼
let source = this.$axios.CancelToken.source(); this.$axios.get('/goods.json',{ cancelToken: source }).then(res=>{ console.log(res) }).catch(err=>{ //取消請求后會(huì)執(zhí)行該方法 console.log(err) }) //取消請求,參數(shù)可選,該參數(shù)信息會(huì)發(fā)送到請求的catch中 source.cancel('取消后的信息');
(學(xué)習(xí)視頻分享:web前端開發(fā)、編程基礎(chǔ)視頻)