2.3.4 • Published 5 years ago

slim-fetch v2.3.4

Weekly downloads
6
License
MIT
Repository
github
Last release
5 years ago

slim-fetch

npm version build status coverage status install size

A slimmed-down but feature complete version of node-fetch that brings window.fetch to Node.js

For the upstream project, visit bitinn/node-fetch

Note: I did not create this project, I only removed unnecessary files from the original to save on package size.

Seeing as this library is designed to be as small as possible from a package size, some documentation has been stripped from this file. For the full documentation, please visit bitinn/node-fetch. Links in the table of contents have been updated to point upstream.

Motivation

Instead of implementing XMLHttpRequest in Node.js to run browser-specific Fetch polyfill, why not go from native http to fetch API directly? Hence node-fetch, minimal code for a window.fetch compatible API on Node.js runtime.

See Matt Andrews' isomorphic-fetch or Leonardo Quixada's cross-fetch for isomorphic usage (exports node-fetch for server-side, whatwg-fetch for client-side).

Features

  • Stay consistent with window.fetch API.
  • Make conscious trade-off when following WHATWG fetch spec and stream spec implementation details, document known differences.
  • Use native promise, but allow substituting it with insert your favorite promise library.
  • Use native Node streams for body, on both request and response.
  • Decode content encoding (gzip/deflate) properly, and convert string output (such as res.text() and res.json()) to UTF-8 automatically.
  • Useful extensions such as timeout, redirect limit, response size limit, explicit errors for troubleshooting.

Difference from client-side fetch

  • See Known Differences for details.
  • If you happen to use a missing feature that window.fetch offers, feel free to open an issue.
  • Pull requests are welcomed too!

Installation

Current stable release (2.x)

$ npm install slim-fetch --save

Loading and configuring the module

We suggest you load the module via require, pending the stabalizing of es modules in node:

const fetch = require('slim-fetch');

If you are using a Promise library other than native, set it through fetch.Promise:

const Bluebird = require('bluebird');

fetch.Promise = Bluebird;

Common Usage

NOTE: The documentation below is up-to-date with 2.x releases, see 1.x readme, changelog and 2.x upgrade guide for the differences.

Plain text or HTML

fetch('https://github.com/')
    .then(res => res.text())
    .then(body => console.log(body));

JSON

fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(json => console.log(json));

Simple Post

fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
    .then(res => res.json()) // expecting a json response
    .then(json => console.log(json));

Post with JSON

const body = { a: 1 };

fetch('https://httpbin.org/post', {
        method: 'post',
        body:    JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' },
    })
    .then(res => res.json())
    .then(json => console.log(json));

Post with form parameters

URLSearchParams is available in Node.js as of v7.5.0. See official documentation for more usage methods.

NOTE: The Content-Type header is only set automatically to x-www-form-urlencoded when an instance of URLSearchParams is given as such:

const { URLSearchParams } = require('url');

const params = new URLSearchParams();
params.append('a', 1);

fetch('https://httpbin.org/post', { method: 'POST', body: params })
    .then(res => res.json())
    .then(json => console.log(json));

Handling exceptions

NOTE: 3xx-5xx responses are NOT exceptions, and should be handled in then(), see the next section.

Adding a catch to the fetch promise chain will catch all exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the error handling document for more details.

fetch('https://domain.invalid/')
    .catch(err => console.error(err));

Handling client and server errors

It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:

function checkStatus(res) {
    if (res.ok) { // res.status >= 200 && res.status < 300
        return res;
    } else {
        throw MyCustomError(res.statusText);
    }
}

fetch('https://httpbin.org/status/400')
    .then(checkStatus)
    .then(res => console.log('will not get here...'))

Advanced Usage

Full documentation for advanced documentation can be found at bitinn/node-fetch#advanced-usage

API

Full API documentation can be found at bitinn/node-fetch#API

Acknowledgement

Thanks to github/fetch for providing a solid implementation reference.

slim-fetch is a minified version of node-fetch maintained by @leonm1. node-fetch v1 was maintained by @bitinn, v2 is currently maintained by @TimothyGu, v2 readme is written by @jkantr.

License

MIT

2.3.4

5 years ago

2.3.3

5 years ago

2.3.2

5 years ago

2.3.1

5 years ago

2.3.0

5 years ago