zlFetch는 편리한 요청 방법을 제공하는 가져오기 래퍼입니다.
그 특징은 다음과 같습니다.
기본 가져 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
개체가 표시됩니다.
url
method
headers
body
zlFetch ( 'url' , { debug : true } )
. then ( { debug } = > console . log ( debug ) )
zlFetch는 모든 400 및 500 오류를 catch
메서드로 보냅니다. 오류에는 응답과 동일한 정보가 포함됩니다.
headers
: 응답 헤더body
: 응답 본문status
: 응답 상태statusText
: 응답 상태 텍스트response
: 가져오기의 원래 응답이는 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
의 새로운 기능
이제 URL을 전달하지 않고도 zlFetch
인스턴스를 사용할 수 있습니다. 이는 올바른 엔드포인트를 사용하여 인스턴스를 생성한 경우 유용합니다.
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
옵션에 전달할 수 있습니다. 이는 zlFetch의 추가 처리 없이 일반 Fetch 요청의 응답을 반환합니다. 그런 다음 response.json()
또는 적절하다고 판단되는 다른 방법을 사용할 수 있습니다.
const response = await zlFetch ( 'url' , {
customResponseParser : true ,
} )
const data = await response . arrayBuffer ( )