페치 API를 Node.js로 가져 오는 가벼운 모듈

V2 문서를 찾고있을 수 있습니다
Node.js에서 XMLHttpRequest 구현하여 브라우저 별 페치 폴리 필을 실행하는 대신 기본 http 에서 API를 직접 fetch 오는 것이 어떻습니까? 따라서 Node.js 런타임의 window.fetch 호환 API의 최소 코드, node-fetch , 최소 코드.
동맥류 사용을위한 Jason Miller의 동형 불꽃 또는 Leonardo Quixada의 크로스 페치를 참조하십시오 (서버 측의 경우 node-fetch , 클라이언트 측을위한 whatwg-fetch ).
window.fetch API와 일치합니다.res.text() 및 res.json() )을 자동으로 UTF-8로 변환합니다.window.fetch 제공하는 경우 자유롭게 문제를여십시오. 현재 안정적인 릴리스 ( 3.x )는 최소 node.js 12.20.0을 필요로합니다.
npm install node-fetch import fetch from 'node-fetch' ; V3의 node-fetch 는 ESM 전용 모듈입니다. require() 으로 가져올 수 없습니다.
ESM으로 전환 할 수없는 경우 CommonJS와 호환되는 V2를 사용하십시오. v2 용 중요한 버그 수정이 계속 게시됩니다.
npm install node-fetch@2 또는 CommonJS의 Async import() 함수를 사용하여 node-fetch 비동기로로드 할 수 있습니다.
// mod.cjs
const fetch = ( ... args ) => import ( 'node-fetch' ) . then ( ( { default : fetch } ) => fetch ( ... args ) ) ; 가져 오기 ()을 가져 오지 않고 fetch() 사용하려면 노드에서 global 객체를 패치 할 수 있습니다.
// fetch-polyfill.js
import fetch , {
Blob ,
blobFrom ,
blobFromSync ,
File ,
fileFrom ,
fileFromSync ,
FormData ,
Headers ,
Request ,
Response ,
} from 'node-fetch'
if ( ! globalThis . fetch ) {
globalThis . fetch = fetch
globalThis . Headers = Headers
globalThis . Request = Request
globalThis . Response = Response
}
// index.js
import './fetch-polyfill'
// ... 기존 버전의 노드 페치 사용? 다음 파일을 확인하십시오.
참고 : 아래 문서는 3.x 릴리스와 함께 최신입니다. 이전 버전을 사용하는 경우 업그레이드 방법을 확인하십시오.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://github.com/' ) ;
const body = await response . text ( ) ;
console . log ( body ) ; import fetch from 'node-fetch' ;
const response = await fetch ( 'https://api.github.com/users/github' ) ;
const data = await response . json ( ) ;
console . log ( data ) ; import fetch from 'node-fetch' ;
const response = await fetch ( 'https://httpbin.org/post' , { method : 'POST' , body : 'a=1' } ) ;
const data = await response . json ( ) ;
console . log ( data ) ; import fetch from 'node-fetch' ;
const body = { a : 1 } ;
const response = await fetch ( 'https://httpbin.org/post' , {
method : 'post' ,
body : JSON . stringify ( body ) ,
headers : { 'Content-Type' : 'application/json' }
} ) ;
const data = await response . json ( ) ;
console . log ( data ) ; URLSearchParams v10.0.0 기준으로 node.js의 Global Object에서 사용할 수 있습니다. 더 많은 사용 방법은 공식 문서를 참조하십시오.
참고 : Content-Type 헤더는 URLSearchParams 인스턴스가 다음과 같이 표시 될 때 x-www-form-urlencoded 로 자동 설정됩니다.
import fetch from 'node-fetch' ;
const params = new URLSearchParams ( ) ;
params . append ( 'a' , 1 ) ;
const response = await fetch ( 'https://httpbin.org/post' , { method : 'POST' , body : params } ) ;
const data = await response . json ( ) ;
console . log ( data ) ; 참고 : 3xx-5xx 응답은 예외가 아니며 다음 then() 을 참조하십시오.
Fetch 함수를 try/catch 블록으로 래핑하면 네트워크 오류와 같은 노드 핵심 라이브러리에서 유래 한 오류 및 FetchError의 인스턴스 인 작동 오류와 같은 모든 예외를 포착합니다. 자세한 내용은 오류 처리 문서를 참조하십시오.
import fetch from 'node-fetch' ;
try {
await fetch ( 'https://domain.invalid/' ) ;
} catch ( error ) {
console . log ( error ) ;
}응답에 클라이언트 (4xx) 또는 서버 (5xx) 오류 응답이 포함되어 있는지 확인하기 위해 도우미 기능을 작성하는 것이 일반적입니다.
import fetch from 'node-fetch' ;
class HTTPResponseError extends Error {
constructor ( response ) {
super ( `HTTP Error Response: ${ response . status } ${ response . statusText } ` ) ;
this . response = response ;
}
}
const checkStatus = response => {
if ( response . ok ) {
// response.status >= 200 && response.status < 300
return response ;
} else {
throw new HTTPResponseError ( response ) ;
}
}
const response = await fetch ( 'https://httpbin.org/status/400' ) ;
try {
checkStatus ( response ) ;
} catch ( error ) {
console . error ( error ) ;
const errorBody = await error . response . text ( ) ;
console . error ( `Error body: ${ errorBody } ` ) ;
}쿠키는 기본적으로 저장되지 않습니다. 그러나 쿠키는 요청 및 응답 헤더를 조작하여 추출하고 전달할 수 있습니다. 자세한 내용은 Set-Cookie 헤더 추출물을 참조하십시오.
"node.js way"는 가능한 경우 스트림을 사용하는 것입니다. 다른 스트림으로 res.body 파이프 할 수 있습니다. 이 예제는 stream.pipeline을 사용하여 스트림 오류 핸들러를 첨부하고 다운로드가 완료 될 때까지 기다립니다.
import { createWriteStream } from 'node:fs' ;
import { pipeline } from 'node:stream' ;
import { promisify } from 'node:util'
import fetch from 'node-fetch' ;
const streamPipeline = promisify ( pipeline ) ;
const response = await fetch ( 'https://github.githubassets.com/images/modules/logos_page/Octocat.png' ) ;
if ( ! response . ok ) throw new Error ( `unexpected response ${ response . statusText } ` ) ;
await streamPipeline ( response . body , createWriteStream ( './octocat.png' ) ) ; Node.js 14에서는 비동기 반복자를 사용하여 body 읽을 수도 있습니다. 그러나 오류를 잡을 수 있도록주의하십시오. 응답이 길어질수록 오류가 발생할 가능성이 높아집니다.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://httpbin.org/stream/3' ) ;
try {
for await ( const chunk of response . body ) {
console . dir ( JSON . parse ( chunk . toString ( ) ) ) ;
}
} catch ( err ) {
console . error ( err . stack ) ;
} Node.js 12에서는 비동기 반복자를 사용하여 body 읽을 수도 있습니다. 그러나 스트림이있는 비동기 반복기는 Node.js 14까지 성숙하지 않았으므로 스트림에서 직접 오류를 처리하고 완전히 닫히기 위해 응답을 기다리려면 추가 작업을 수행해야합니다.
import fetch from 'node-fetch' ;
const read = async body => {
let error ;
body . on ( 'error' , err => {
error = err ;
} ) ;
for await ( const chunk of body ) {
console . dir ( JSON . parse ( chunk . toString ( ) ) ) ;
}
return new Promise ( ( resolve , reject ) => {
body . on ( 'close' , ( ) => {
error ? reject ( error ) : resolve ( ) ;
} ) ;
} ) ;
} ;
try {
const response = await fetch ( 'https://httpbin.org/stream/3' ) ;
await read ( response . body ) ;
} catch ( err ) {
console . error ( err . stack ) ;
} import fetch from 'node-fetch' ;
const response = await fetch ( 'https://github.com/' ) ;
console . log ( response . ok ) ;
console . log ( response . status ) ;
console . log ( response . statusText ) ;
console . log ( response . headers . raw ( ) ) ;
console . log ( response . headers . get ( 'content-type' ) ) ; 브라우저와 달리 Headers.raw() 사용하여 수동으로 원시 Set-Cookie 헤더에 액세스 할 수 있습니다. 이것은 node-fetch 전용 API입니다.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://example.com' ) ;
// Returns an array of values, instead of a string of comma-separated values
console . log ( response . headers . raw ( ) [ 'set-cookie' ] ) ; import fetch , {
Blob ,
blobFrom ,
blobFromSync ,
File ,
fileFrom ,
fileFromSync ,
} from 'node-fetch'
const mimetype = 'text/plain'
const blob = fileFromSync ( './input.txt' , mimetype )
const url = 'https://httpbin.org/post'
const response = await fetch ( url , { method : 'POST' , body : blob } )
const data = await response . json ( )
console . log ( data )Node-Fetch는 Multipart/Form-Data Payloads를 게시하기위한 Spec Compliant FormData 구현과 함께 제공됩니다.
import fetch , { FormData , File , fileFrom } from 'node-fetch'
const httpbin = 'https://httpbin.org/post'
const formData = new FormData ( )
const binary = new Uint8Array ( [ 97 , 98 , 99 ] )
const abc = new File ( [ binary ] , 'abc.txt' , { type : 'text/plain' } )
formData . set ( 'greeting' , 'Hello, world!' )
formData . set ( 'file-upload' , abc , 'new name.txt' )
const response = await fetch ( httpbin , { method : 'POST' , body : formData } )
const data = await response . json ( )
console . log ( data )어떤 이유로 든 임의의 장소에서 나오는 스트림을 게시 해야하는 경우 블로브 나 파일 모양의 항목을 추가 할 수 있습니다.
최소 요구 사항은 다음과 같습니다.
Symbol.toStringTag getter 또는 Blob 또는 File 속성stream() 메소드 또는 arrayBuffer() 메소드. stream() Uint8Array (또는 버퍼)를 생성하여 Node.Readable 스트림과 WhatWG 스트림이 잘 작동하는 한 비동기 반복 가능한 물체를 반환해야합니다.
formData . append ( 'upload' , {
[ Symbol . toStringTag ] : 'Blob' ,
size : 3 ,
* stream ( ) {
yield new Uint8Array ( [ 97 , 98 , 99 ] )
} ,
arrayBuffer ( ) {
return new Uint8Array ( [ 97 , 98 , 99 ] ) . buffer
}
} , 'abc.txt' ) AbortController 로 요청을 취소 할 수 있습니다. 제안 된 구현은 abort-controller 입니다.
150ms 이후의 요청시기의 예는 다음과 같이 달성 될 수 있습니다.
import fetch , { AbortError } from 'node-fetch' ;
// AbortController was added in node v14.17.0 globally
const AbortController = globalThis . AbortController || await import ( 'abort-controller' )
const controller = new AbortController ( ) ;
const timeout = setTimeout ( ( ) => {
controller . abort ( ) ;
} , 150 ) ;
try {
const response = await fetch ( 'https://example.com' , { signal : controller . signal } ) ;
const data = await response . json ( ) ;
} catch ( error ) {
if ( error instanceof AbortError ) {
console . log ( 'request was aborted' ) ;
}
} finally {
clearTimeout ( timeout ) ;
}더 많은 예는 테스트 사례를 참조하십시오.
url 페치를위한 URL을 나타내는 문자열options 옵션Promise<Response>HTTP 페치를 수행하십시오.
url https://example.com/ 과 같은 절대 URL이어야합니다. 경로 관련 URL ( /file/under/root ) 또는 프로토콜 관련 URL ( //can-be-http-or-https.com/ )은 거부 된 Promise 초래합니다.
각 옵션 키 후에 기본값이 표시됩니다.
{
// These properties are part of the Fetch Standard
method : 'GET' ,
headers : { } , // Request headers. format is the identical to that accepted by the Headers constructor (see below)
body : null , // Request body. can be null, or a Node.js Readable stream
redirect : 'follow' , // Set to `manual` to extract redirect headers, `error` to reject redirect
signal : null , // Pass an instance of AbortSignal to optionally abort requests
// The following properties are node-fetch extensions
follow : 20 , // maximum redirect count. 0 to not follow redirect
compress : true , // support gzip/deflate content encoding. false to disable
size : 0 , // maximum response body size in bytes. 0 to disable
agent : null , // http(s).Agent instance or function that returns an instance (see below)
highWaterMark : 16384 , // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
insecureHTTPParser : false // Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
} 값이 설정되지 않으면 다음 요청 헤더가 자동으로 전송됩니다.
| 헤더 | 값 |
|---|---|
Accept-Encoding | gzip, deflate, br ( options.compress === true ) |
Accept | */* |
Content-Length | (가능하면 자동으로 계산) |
Host | (대상 URI의 호스트 및 포트 정보) |
Transfer-Encoding | chunked ( req.body 가 스트림 일 때) |
User-Agent | node-fetch |
참고 : body 가 Stream 인 경우 Content-Length 자동으로 설정되지 않습니다.
agent 옵션을 사용하면 다음을 포함하여 Fetch 범위를 벗어난 네트워킹 관련 옵션을 지정할 수 있습니다.
자세한 내용은 http.Agent 참조하십시오.
에이전트가 지정되지 않으면 Node.js가 제공하는 기본 에이전트가 사용됩니다. 이는 기본적으로 keepalive true로 Node.js 19에서 변경되었습니다. 이전 버전의 node.js에서 keepalive 활성화하려면 다음 코드 샘플에 따라 에이전트를 대체 할 수 있습니다.
또한 agent 옵션은 http 를 반환하는 함수를 .Agent 합니다.
import http from 'node:http' ;
import https from 'node:https' ;
const httpAgent = new http . Agent ( {
keepAlive : true
} ) ;
const httpsAgent = new https . Agent ( {
keepAlive : true
} ) ;
const options = {
agent : function ( _parsedURL ) {
if ( _parsedURL . protocol == 'http:' ) {
return httpAgent ;
} else {
return httpsAgent ;
}
}
} ; Node.js의 스트림에는 클라이언트 측 브라우저 (> 1MB, 브라우저에서 일관되지 않음)에서 내부 버퍼 크기가 더 작습니다 (16KB, 일명 highWaterMark ). 이로 인해 동형 앱을 작성하고 res.clone() 사용하면 노드에서 큰 응답으로 매달려 있습니다.
이 문제를 해결하는 권장 방법은 복제 된 응답을 동시에 해결하는 것입니다.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://example.com' ) ;
const r1 = response . clone ( ) ;
const results = await Promise . all ( [ response . json ( ) , r1 . text ( ) ] ) ;
console . log ( results [ 0 ] ) ;
console . log ( results [ 1 ] ) ; 어떤 이유로 위의 솔루션이 마음에 들지 않으면 3.x 이므로 highWaterMark 옵션을 수정할 수 있습니다.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://example.com' , {
// About 1MB
highWaterMark : 1024 * 1024
} ) ;
const result = await res . clone ( ) . arrayBuffer ( ) ;
console . dir ( result ) ; http (s) .request의 insecureHTTPParser 옵션으로 전달되었습니다. 자세한 내용은 http.request 참조하십시오.
노드 페치의 redirect: 'manual' 옵션은 브라우저 및 사양과 다르기 때문에 불투명 한 편집 된 필터링 응답이 발생합니다. Node-Fetch는 대신 일반적인 기본 필터링 응답을 제공합니다.
import fetch from 'node-fetch' ;
const response = await fetch ( 'https://httpbin.org/status/301' , { redirect : 'manual' } ) ;
if ( response . status === 301 || response . status === 302 ) {
const locationURL = new URL ( response . headers . get ( 'location' ) , response . url ) ;
const response2 = await fetch ( locationURL , { redirect : 'manual' } ) ;
console . dir ( response2 ) ;
}URL, 방법, 헤더 및 본문에 대한 정보가 포함 된 HTTP 요청. 이 클래스는 차체 인터페이스를 구현합니다.
Node.js의 특성으로 인해 현재 다음 속성이 구현되지 않습니다.
typedestinationmodecredentialscacheintegritykeepalive다음 노드 페치 확장 속성이 제공됩니다.
followcompresscounteragenthighWaterMark이러한 확장의 정확한 의미는 옵션을 참조하십시오.
(사양 준수)
Request input (복제됩니다)options 옵션 새 Request 객체를 구성합니다. 생성자는 브라우저의 생성자와 동일합니다.
대부분의 경우 직접 fetch(url, options) Request 객체를 만드는 것보다 간단합니다.
HTTP 응답. 이 클래스는 차체 인터페이스를 구현합니다.
현재 Node-Fetch에서는 다음 속성이 구현되지 않습니다.
trailer(사양 준수)
body String 또는 Readable 스트림options ResponseInit 옵션 옵션 사전 새로운 Response 객체를 구성합니다. 생성자는 브라우저의 생성자와 동일합니다.
Node.js는 서비스 작업자 (이 클래스가 설계된)를 구현하지 않기 때문에 직접 Response 직접 구성 할 필요는 없습니다.
(사양 준수)
요청이 정상적으로 종료 된 경우를 나타내는 편의 속성. 응답 상태가 200보다 크지 만 300보다 작 으면 TRUE를 평가합니다.
(사양 준수)
요청이 적어도 한 번은 리디렉션 된 경우를 나타내는 편의 속성. 내부 리디렉션 카운터가 0보다 큰 경우 true로 평가됩니다.
(사양에서 편차)
응답 유형을 나타내는 편의 속성. 노드 페치는 'default' 및 'error' 만 지원하며 필터링 된 응답을 사용하지 않습니다.
이 클래스를 사용하면 HTTP 헤더 세트를 조작하고 반복 할 수 있습니다. 페치 표준에 지정된 모든 방법이 구현됩니다.
(사양 준수)
Headers 개체를 미리 채우기 위해 선택적 인수를 init 새 Headers 개체를 구성하십시오. init null , Headers 개체, 키 값 맵 객체 또는 반복 가능한 객체 일 수 있습니다.
// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
import { Headers } from 'node-fetch' ;
const meta = {
'Content-Type' : 'text/xml'
} ;
const headers = new Headers ( meta ) ;
// The above is equivalent to
const meta = [ [ 'Content-Type' , 'text/xml' ] ] ;
const headers = new Headers ( meta ) ;
// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map ( ) ;
meta . set ( 'Content-Type' , 'text/xml' ) ;
const headers = new Headers ( meta ) ;
const copyOfHeaders = new Headers ( headers ) ; Body Request 및 Response 클래스 모두에 적용 가능한 방법을 갖춘 추상 인터페이스입니다.
(사양에서 편차)
Readable 스트림 데이터는 Body 물체에 캡슐화됩니다. Fetch 표준은 속성이 항상 Whatwg ReadableStream 이어야하지만 Node-Fetch에서는 Node.js Readable Stream입니다.
(사양 준수)
Boolean이 기관이 소비 된 경우 부울 재산. 사양에 따라 소비 된 몸체를 다시 사용할 수 없습니다.
fetch .formData() 사용하여 multipart/form-data 페이로드와 x-www-form-urlencoded 체 바디를 구문 분석하는 방법이 제공됩니다. 이는 서비스 작업자가 서버로 전송되기 전에 해당 메시지를 변경하여 변경하기 전에 해당 메시지를 가로 채울 수 있다는 아이디어에서 비롯됩니다. 이는 서버를 구축하는 사람에게 유용하므로 페이로드를 구문 분석하고 소비 할 수 있습니다.
import http from 'node:http'
import { Response } from 'node-fetch'
http . createServer ( async function ( req , res ) {
const formData = await new Response ( req , {
headers : req . headers // Pass along the boundary value
} ) . formData ( )
const allFields = [ ... formData ]
const file = formData . get ( 'uploaded-files' )
const arrayBuffer = await file . arrayBuffer ( )
const text = await file . text ( )
const whatwgReadableStream = file . stream ( )
// other was to consume the request could be to do:
const json = await new Response ( req ) . json ( )
const text = await new Response ( req ) . text ( )
const arrayBuffer = await new Response ( req ) . arrayBuffer ( )
const blob = await new Response ( req , {
headers : req . headers // So that `type` inherits `Content-Type`
} . blob ( )
} )(노드 페치 확장)
페치 프로세스에서 작동 오류. 자세한 내용은 Error-Handling.md를 참조하십시오.
(노드 페치 확장)
AbortSignal 의 abort 이벤트에 대한 응답으로 요청이 중단 될 때 발생하는 오류. AbortError 의 name 속성이 있습니다. 자세한 내용은 Error-Handling.md를 참조하십시오.
3.x 유형은 node-fetch 와 번들로 제공되므로 추가 패키지를 설치할 필요가 없습니다.
이전 버전의 경우 확실히 다음의 유형 정의를 사용하십시오.
npm install --save-dev @types/[email protected]견고한 구현 참조를 제공 한 GitHub/Fetch에게 감사드립니다.
![]() | ![]() | ![]() | ![]() | ![]() |
|---|---|---|---|---|
| 데이비드 프랭크 | 지미 Wärting | 안토니 케핀 스키 | Richie Bendall | 그레고르 마티 누스 |
MIT