2020-03-19(axios)

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 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 配置默認值

????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]])

注釋

當使用以上別名方法時,url,method和data等屬性不用在config重復聲明

??<script>

????axios({

??????//?注意:只有url是必填,默認的請求方法是GET

??????url:?'/user',//?`url`?是請求的接口地址

??????method:?'get',//?`method`?是請求的方法?默認值是get

??????baseURL:?'https://some-domain.com/api/',//?如果url不是絕對路徑,那么會將baseURL和url拼接作為請求的接口地址

??????//?用于請求之前對請求數(shù)據(jù)進行操作

??????//?只用當請求方法為‘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ù)負責序列化`params`

????????return?Qs.stringify(params,?{arrayFormat:?'brackets'})

??????},

??????//?請求體數(shù)據(jù)

??????//?只有當請求方法為'PUT',?'POST',和'PATCH'時可用

??????//?當沒有設(shè)置`transformRequest`時,必須是以下幾種格式

??????//?-?string,?plain?object,?ArrayBuffer,?ArrayBufferView,?URLSearchParams

??????//?-?Browser?only:?FormData,?File,?Blob

??????//?-?Node?only:?Stream,?Buffer

??????data:?{firstName:?'Fred'},

??????timeout:?1000,//?請求超時時間(毫秒)

??????withCredentials:?false,?//?默認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',?//?默認值是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)默認,優(yōu)先級高的覆蓋優(yōu)先級低的。

????var?instance?=?axios.create();//?創(chuàng)建一個實例,這時的超時時間為系統(tǒng)默認的?0

????//?通過instance.defaults重新設(shè)置超時時間為2.5s,因為優(yōu)先級比系統(tǒng)默認高

????instance.defaults.timeout?=?2500;

??</script>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • axios 基于 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 node.js 中使用 功能特性 在...
    Yanghc閱讀 3,744評論 0 7
  • 一、安裝 1、 利用npm安裝npm install axios --save 2、 利用bower安裝bower...
    kiddings閱讀 1,911評論 0 3
  • 我們在實際的Vue項目中經(jīng)常需要與后端進行數(shù)據(jù)交互,但是在很大程度上我們需要用到這個插件,但是這里需要注意的一點是...
    Marin_chen閱讀 11,077評論 0 5
  • axios 基于 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 node.js 中使用 功能特性 在...
    jslxm閱讀 4,477評論 0 1
  • 準備工作 vue-cli 創(chuàng)建一個新項目 vue-cli axios中文說明文檔 1.安裝axios npm in...
    趙偉敏_19閱讀 2,374評論 0 16

友情鏈接更多精彩內(nèi)容