封裝axios和fetch方法

2021-09-29 15:24:32 字數 1981 閱讀 9467

比較兩種請求方式

3.比較fetch和axios

fetch並沒有進行封裝,拿到就是格式化後的資料

3.更多詳情請參考:axios和fetch請求詳解

axios封裝

/* 

封裝一下axios

! 它是乙個函式,因為它要攜帶引數

*/function

request()

).then

( res =>

resolve

( res )).

catch

( err =>

reject

( err )

)break

;case

'post'

: console.

log(

'post - p'

)const p =

newurlsearchparams()

// data

if( data )

}axios()

.then

( res =>

resolve

( res )).

catch

( err =>

reject

( err )

)break

;case

'put'

:axios()

.then

( res =>

resolve

( res )).

catch

( err =>

reject

( err )

)break

;case

'delete'

:axios()

.then

( res =>

resolve

( res )).

catch

( err =>

reject

( err )

)break

;default

:break;}

})}

fetch請求封裝

/**

* 將物件轉成 a=1&b=2的形式

* @param obj 物件

*/function

obj2string

(obj, arr =

, idx =0)

return

newurlsearchparams

(arr)

.tostring()

}/**

* 真正的請求

* @param url 請求位址

* @param options 請求引數

* @param method 請求方式

*/function

commonfetcdh

(url, options, method =

'get')if

(method ===

'get')}

else),

body: searchstr

}}fetch

(url, initobj)

.then

((res)

=>).

then

((res)

=>)}

/** * get請求

* @param url 請求位址

* @param options 請求引數

*/function

get(url, options)

/** * post請求

* @param url 請求位址

* @param options 請求引數

*/function

post

(url, options)

get(

'',)

post

('',)

Fetch封裝方法

fetch是乙個與ajax請求功能相似的乙個請求介面,並且只有瀏覽器該方法。fetch的出現一方面是為了緩解原生xmlhttprequest實現起來比較雜亂的問題。下面是乙個例子 用xhr物件實現ajax請求 xhr.send 用fetch實現ajax請求 fetch url,then res th...

fetch和axios區別比較

try catch e 特點 缺點 1 fetch只對網路請求報錯,對400,500都當做成功的請求,需要封裝去處理 2 fetch預設不會帶cookie,需要新增配置項 3 fetch不支援abort,不支援超時控制,使用settimeout及promise.reject的實現的超時控制並不能阻止...

axios和 fetch的使用

3.1 axios fetch 目的 是在框架中使用資料請求 回顧 封裝ajax jquery ge t.get get post aj ax ajax aja x load 框架 資料請求 使用原生js提供的fetch 使用第三方封裝庫 axios vue中可以統一對axios進行掛載 vue r...