? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? axios
基于promise用于瀏覽器和node.js的http客戶端
1.特點:
1.支持瀏覽器和node.js
2.瀏覽器端支持防止CSRF(跨站請求偽造)
3.支持promise
4.能夠攔截請求和響應(yīng)
5.能夠轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
6.能取消請求
7.它能自動轉(zhuǎn)換為json的數(shù)據(jù)
2.如何使用
1.安裝 npm install --save axios
2.在main.js或者index.js
import axios from "axios"
Vue.prototype.$http=axios
3.基本的api的方法
1.執(zhí)行g(shù)et請求窄驹,有兩種方式
? 第一種方式:將參數(shù)直接寫在url中
axios.get("/getName?id=12").then((res)=>{}).catch((err)=>{})
? 第二種方式:將參數(shù)寫在params中
axios.get("/getName",{params:{id:12}}).then((res)=>{}).catch((err)=>{})
??created(){
????//?this.$http?等價于?axios
????this.$http.get("https://xxdfg/uuuuil/klkl?id=14").then((res)?=>?{
??????console.log(res)
????});
????this.$http.get("https://xxdfg/uuuuil/klkl",{params:{id:14}}).then((res)?=>?{
??????console.log(res)
????})
??}
????2.執(zhí)行post請求袭景,注意執(zhí)行post請求的參數(shù)的時候,不需要寫params字段中嗜暴,這里要注意和get請求的第二種方式區(qū)別開來
axios.post("/getName",{id:123}).then((res)=>{}).catch((err)=>{})
4.通過向axios傳遞相關(guān)的配置來創(chuàng)建請求
????url:請求路徑 string類型
????method:請求的方法
????baseURL:baseURL會自動加載url的前面
????headers:自定義請求消息頭
????params: 用來傳遞參數(shù) ?
????timeout:超時的時間精堕,超過時間孵淘,請求就會終止
????基本方式發(fā)送post請求
????axios({
????????method:"post",
????????url:“”
????})
5 配置默認(rèn)值
????axios.default.baseURL=""
????axios.default.headers.common["sk"]=auto_token;
? ? axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded';
6.執(zhí)行多個并發(fā)
axios.all()和promise.all()的機制是一樣的锄码,都是可以執(zhí)行多個并發(fā)夺英,要么全部成功走then晌涕,要么就走catch
function getName(){
return ?axios.get("/getName")
}
function getAge(){
return ?axios.get("/getAge")
}
axios.all([getName(),getAge()]).then((res)=>{}).catch((err)=>{
})
7.攔截器
1.在請求之前攔截請求
//添加請求攔截器
axios.interceptors.request.use(function(config){
//發(fā)送請求之前做了什么事情
return config
},function(err){
//對請求的錯誤做了什么
return Promise.reject(err)
})
2.在響應(yīng)的時候進行攔截
axios.interceptors.response.use(function(response){
//對響應(yīng)的數(shù)據(jù)做什么操作
return response
},function(err){
//對請求的錯誤做了什么
return Promise.reject(err)
})
8.請求方法別名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
注釋
當(dāng)使用以上別名方法時,url痛悯,method和data等屬性不用在config重復(fù)聲明
??<script>
????axios({
??????//?注意:只有url是必填余黎,默認(rèn)的請求方法是GET
??????url:?'/user',//?`url`?是請求的接口地址
??????method:?'get',//?`method`?是請求的方法?默認(rèn)值是get
??????baseURL:?'https://some-domain.com/api/',//?如果url不是絕對路徑,那么會將baseURL和url拼接作為請求的接口地址
??????//?用于請求之前對請求數(shù)據(jù)進行操作
??????//?只用當(dāng)請求方法為‘PUT’载萌,‘POST’和‘PATCH’時可用
??????//?函數(shù)需return出相應(yīng)數(shù)據(jù)
??????//?可以修改headers
??????transformRequest:?[function?(data,?headers)?{
??????????return?data;//?可以對data做任何操作
??????}],
??????//?用于對相應(yīng)數(shù)據(jù)進行處理
??????//?它會通過then或者catch
??????transformResponse:?[function?(data)?{
??????????return?data;//?可以對data做任何操作
??????}],
??????headers:?{'X-Requested-With':?'XMLHttpRequest'},//?請求消息頭
??????params:?{ID:?12345},//?URL參數(shù)必須是一個純對象或者?URL參數(shù)對象
??????paramsSerializer:?function(params)?{//?是一個可選的函數(shù)負(fù)責(zé)序列化`params`
????????return?Qs.stringify(params,?{arrayFormat:?'brackets'})
??????},
??????//?請求體數(shù)據(jù)
??????//?只有當(dāng)請求方法為'PUT',?'POST',和'PATCH'時可用
??????//?當(dāng)沒有設(shè)置`transformRequest`時惧财,必須是以下幾種格式
??????//?-?string,?plain?object,?ArrayBuffer,?ArrayBufferView,?URLSearchParams
??????//?-?Browser?only:?FormData,?File,?Blob
??????//?-?Node?only:?Stream,?Buffer
??????data:?{firstName:?'Fred'},
??????timeout:?1000,//?請求超時時間(毫秒)
??????withCredentials:?false,?//?默認(rèn)default,是否攜帶cookie信息
??????adapter:?function?(config)?{},//?統(tǒng)一處理request讓測試更加容易扭仁,返回一個promise并提供一個可用的response
??????auth:?{
????????username:?'janedoe',
????????password:?'s00pers3cret'
??????},
??????//?響應(yīng)格式
??????//?可選項?'arraybuffer',?'blob',?'document',?'json',?'text',?'stream'
??????responseType:?'json',?//?默認(rèn)值是json
??????xsrfCookieName:?'XSRF-TOKEN',?//?default
??????xsrfHeaderName:?'X-XSRF-TOKEN',?//?default
??????onUploadProgress:?function?(progressEvent)?{},//?處理上傳進度事件
??????onDownloadProgress:?function?(progressEvent)?{},//?處理下載進度事件
??????maxContentLength:?2000,//?設(shè)置http響應(yīng)內(nèi)容的最大長度
??????//?定義可獲得的http響應(yīng)狀態(tài)碼
??????//?return?true垮衷、設(shè)置為null或者undefined,promise將resolved,否則將rejected
??????validateStatus:?function?(status)?{
????????return?status?>=?200?&&?status?<?300;?//?default
??????},
??????maxRedirects:?5,?//?default?最大重定向次數(shù)
??????httpAgent:?new?http.Agent({?keepAlive:?true?}),
??????httpsAgent:?new?https.Agent({?keepAlive:?true?}),
??????proxy:?{
????????host:?'127.0.0.1',
????????port:?9000,
????????auth:?{
??????????username:?'mikeymike',
??????????password:?'rapunz3l'
????????}
??????},
??????cancelToken:?new?CancelToken(function?(cancel)?{})//字面上是取消token值
????})
??</script>
??<script>
????//?response響應(yīng)組成
????({
??????data:?{},//?服務(wù)端返回的數(shù)據(jù)
??????status:?200,//?服務(wù)端返回的狀態(tài)碼
??????statusText:?'OK',//?服務(wù)端返回的狀態(tài)信息
??????headers:?{},//?響應(yīng)頭,所有的響應(yīng)頭名稱都是小寫
??????config:?{},//?請求配置
??????request:?{}//?請求
????})
????//?注意:他們返回的是promise用then接收以下響應(yīng)信息
????axios.get('/user/12345').then(function(response)?{
??????console.log(response.data);
??????console.log(response.status);
??????console.log(response.statusText);
??????console.log(response.headers);
??????console.log(response.config);
????});
??</script>
<script>
????//?創(chuàng)建實例時修改配置
????var?instance?=?axios.create({
??????baseURL:?''
????});
????//?實例創(chuàng)建之后修改配置
????instance.defaults.headers.common['Authorization']?=?AUTH_TOKEN;
????//?配置項通過一定的規(guī)則合并乖坠,request?config?>?instance.defaults?>?系統(tǒng)默認(rèn)搀突,優(yōu)先級高的覆蓋優(yōu)先級低的。
????var?instance?=?axios.create();//?創(chuàng)建一個實例熊泵,這時的超時時間為系統(tǒng)默認(rèn)的?0
????//?通過instance.defaults重新設(shè)置超時時間為2.5s仰迁,因為優(yōu)先級比系統(tǒng)默認(rèn)高
????instance.defaults.timeout?=?2500;
??</script>