Simple Promise-based HTTP client for Node.js
- Promise-based
- Simple API that's similar to the Fetch API
- Supports the full Request API
- Supports the full Headers API
- Powered by the built-in http and https modules
- Supports chunked responses
- Supports JSON, ArrayBuffer, Blob, FormData, and text responses
- Supports AbortController, AbortSignal, and timeout
- ESM and CommonJS support
- Lightweight and zero dependencies
npm install @systemsoftware/fetch
Where METHOD
is one of the following: get
, post
, put
, delete
, head
, patch
.
const fetch = require('@systemsoftware/fetch');
fetch.METHOD('https://example.com')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET' })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
const req = new Request('https://example.com', { method: 'GET', headers:new Headers({ 'Content-Type': 'application/json' }) });
fetch(req)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
By default, @systemsoftware/fetch will throw an error if the response status code is not in the range 200-299. To silence these errors, you can use the silent
option and the response will be returned regardless of the status code.
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET', silent: true })
.then(response => response.json())
.then(data => console.log(data))
To abort a request, you can use the AbortController
class.
const { fetch } = require('@systemsoftware/fetch');
const controller = new AbortController();
fetch('https://example.com', { method: 'GET', signal: controller.signal })
controller.abort();
To handle the response data in chunks, you can use the onData
option.
const { fetch } = require('@systemsoftware/fetch');
fetch('https://example.com', { method: 'GET', onData: chunk => console.log(chunk) })
.then(response => console.log('Response finished'))
.catch(error => console.error(error));
The response object is what is returned by the http request, with these additional methods:
-
json
- A promise that returns the response body as JSON -
text
- A promise that returns the response body as text -
arrayBuffer
- A promise that returns the response body as an ArrayBuffer -
blob
- A promise that returns the response body as a Blob