zlFetch 是 fetch 的包裝器,為您提供了一種發出請求的便利方法。
其特點如下:
與本機fetch功能相比,生活品質得到改善
response.json() 、 response.text()或response.blob()catch區塊。await時可以輕鬆處理錯誤-可以傳回錯誤,因此您不必編寫try/catch區塊。本機fetch功能的其他改進
Content-Type標頭會根據body內容自動設定。headers 、 body 、 status等等。GET 、 POST 、 PUT 、 PATCH和DELETE方法的簡寫auth屬性的授權標頭。注意:zlFetch 自v4.0.0起是 ESM 函式庫。
# Installing through npm
npm install zl-fetch --save然後您可以透過將其導入 JavaScript 文件來使用它。
import zlFetch from 'zl-fetch'npm情況下使用zlFetch :您可以透過 CDN 將 zlFetch 直接匯入 JavaScript。
為此,您首先需要將script的類型設為module ,然後匯入zlFetch 。
< script type =" module " >
import zlFetch from 'https://cdn.jsdelivr.net/npm/[email protected]/src/index.js'
</ script > 您可以像使用普通的fetch函數一樣使用 zlFetch。唯一的區別是您不必再編寫response.json或response.text方法!
zlFetch 會自動為您處理它,因此您可以直接使用您的回應。
zlFetch ( 'url' )
. then ( response => console . log ( response ) )
. catch ( error => console . log ( error ) )zlFetch 包含這些常見 REST 方法的簡寫方法,因此您可以快速使用它們。
zlFetch . get ( /* some-url */ )
zlFetch . post ( /* some-url */ )
zlFetch . put ( /* some-url */ )
zlFetch . patch ( /* some-url */ )
zlFetch . delete ( /* some-url */ )zlFetch 支援json 、 text和blob回應類型,因此您不必編寫response.json() 、 response.text()或response.blob() 。
目前不支援其他回應類型。如果您需要支援其他回應類型,請考慮使用您自己的回應處理程序
zlFetch 向您發送response對像中所需的所有資料。這包括以下內容:
headers : 回應頭body :回應主體status :回應狀態statusText :回應狀態文本response :來自 Fetch 的原始回應我們這樣做是為了讓您不必自己找出headers 、 status 、 statusText甚至response物件的其餘部分。
v4.0.0中的新增功能:您可以透過新增偵錯選項來偵錯請求debug 。這將顯示一個包含正在建構的請求debug物件。
urlmethodheadersbody zlFetch ( 'url' , { debug : true } )
. then ( { debug } = > console . log ( debug ) )zlFetch 將所有 400 和 500 錯誤定向到catch方法。錯誤包含與回應相同的資訊。
headers : 回應頭body :回應主體status :回應狀態statusText :回應狀態文本response :來自 fetch 的原始回應這使得 zlFetch 非常易於使用 Promise。
zlFetch ( 'some-url' ) . catch ( error => {
/* Handle error */
} )
// The above request can be written in Fetch like this:
fetch ( 'some-url' )
. then ( response => {
if ( ! response . ok ) {
Promise . reject ( response . json )
}
} )
. catch ( error => {
/* Handle error */
} )async / await時輕鬆處理錯誤zlFetch 允許您將所有錯誤傳遞到errors物件中。您可以透過新增returnError選項來做到這一點。當您大量使用async/await時,這非常有用。
const { response , error } = await zlFetch ( 'some-url' , { returnError : true } ) 您可以新增query或queries作為選項,zlFetch 將自動為您建立一個查詢字串。將其與GET請求一起使用。
zlFetch ( 'some-url' , {
queries : {
param1 : 'value1' ,
param2 : 'to encode' ,
} ,
} )
// The above request can be written in Fetch like this:
fetch ( 'url?param1=value1¶m2=to%20encode' )body內容的Content-Type生成zlFetch 根據您的body資料適當設定Content-Type 。它支援三種數據:
如果你傳入一個object ,zlFetch 會將Content-Type設定為application/json 。它還會JSON.stringify你的身體,這樣你就不必自己做。
zlFetch . post ( 'some-url' , {
body : { message : 'Good game' } ,
} )
// The above request is equivalent to this
fetch ( 'some-url' , {
method : 'post' ,
headers : { 'Content-Type' : 'application/json' } ,
body : JSON . stringify ( { message : 'Good game' } ) ,
} ) zlFetch 包含一個toObject幫助器,可讓您將表單資料轉換為物件。這使得使用表單進行 zlFetch 變得非常容易。
import { toObject } from 'zl-fetch'
const data = new FormData ( form . elements )
zlFetch ( 'some-url' , {
body : toObject ( data ) ,
} )如果您傳入一個字串,zlFetch 會將Content-Type設定為application/x-www-form-urlencoded 。
zlFetch 還包含一個toQueryString方法,可以幫助您將物件轉換為查詢字串,以便您可以輕鬆使用此選項。
import { toQueryString } from 'zl-fetch'
zlFetch . post ( 'some-url' , {
body : toQueryString ( { message : 'Good game' } ) ,
} )
// The above request is equivalent to this
fetch ( 'some-url' , {
method : 'post' ,
headers : { 'Content-Type' : 'application/x-www-form-urlencoded' } ,
body : 'message=Good%20game' ,
} )如果您傳入表單數據,zlFetch 將讓本機fetch函數處理Content-Type 。通常,這將使用帶有預設選項的multipart/form-data 。如果您使用它,請確保您的伺服器可以接收multipart/form-data !
import { toObject } from 'zl-fetch'
const data = new FormData ( form . elements )
zlFetch ( 'some-url' , { body : data } )
// The above request is equivalent to this
fetch ( 'some-url' , { body : data } )
// Your server should be able to receive multipart/form-data if you do this. If you're using Express, you can a middleware like multer to make this possible:
import multer from 'multer'
const upload = multer ( )
app . use ( upload . array ( ) ) v5.0.0中的重大變更:如果您傳入Content-Type標頭,zlFetch 將不再設定正文內容的格式。我們希望您能夠傳入正確的資料類型。 (我們必須這樣做才能支援上面提到的新 API)。
如果您為 zlFetch 提供auth屬性,它將為您產生一個授權標頭。
如果您傳入一個string (通常用於令牌),它將產生一個 Bearer Auth。
zlFetch ( 'some-url' , { auth : 'token12345' } )
// The above request can be written in Fetch like this:
fetch ( 'some-url' , {
headers : { Authorization : `Bearer token12345` } ,
} )如果您傳入一個object ,zlFetch 將為您產生一個基本驗證。
zlFetch ( 'some-url' , {
auth : {
username : 'username'
password : '12345678'
}
} )
// The above request can be written in Fetch like this:
fetch ( 'some-url' , {
headers : { Authorization : `Basic ${ btoa ( 'username:12345678' ) } ` }
} ) ;您可以使用預定義選項建立zlFetch的實例。如果您需要發送具有類似options或url請求,這將非常有用。
url為必填項options是可選的 import { createZLFetch } from 'zl-fetch'
// Creating the instance
const api = zlFetch ( baseUrl , options )所有實例也都有速記方法。
// Shorthand methods
const response = api . get ( /* ... */ )
const response = api . post ( /* ... */ )
const response = api . put ( /* ... */ )
const response = api . patch ( /* ... */ )
const response = api . delete ( /* ... */ ) v5.0.0中的新功能
現在您可以使用zlFetch實例而無需傳遞 URL。如果您建立了具有正確端點的實例,這非常有用。
import { createZLFetch } from 'zl-fetch'
// Creating the instance
const api = zlFetch ( baseUrl , options )所有實例也都有速記方法。
// Shorthand methods
const response = api . get ( ) // Without URL, without options
const response = api . get ( 'some-url' ) // With URL, without options
const response = api . post ( 'some-url' , { body : 'message=good+game' } ) // With URL, with options
const response = api . post ( { body : 'message=good+game' } ) // Without URL, with options如果要處理 zlFetch 不支援的回應,可以將customResponseParser: true傳遞到選項中。這將傳回來自正常 Fetch 請求的回應,而無需 zlFetch 進行任何其他處理。然後,您可以使用response.json()或您認為合適的其他方法。
const response = await zlFetch ( 'url' , {
customResponseParser : true ,
} )
const data = await response . arrayBuffer ( )