Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

node-fetch-polyfill

gwicke7.3kMIT2.0.6

A light-weight module that brings window.fetch to node.js

fetch, http, promise

readme

node-fetch

npm version build status coverage status

A light-weight module that brings window.fetch to Node.js

Motivation

I really like the notion of Matt Andrews' isomorphic-fetch: it bridges the API gap between client-side and server-side http requests, so developers have less to worry about.

Instead of implementing XMLHttpRequest in node to run browser-specific fetch polyfill, why not go from node's http to fetch API directly? Node has native stream support, browserify build targets (browsers) don't, so underneath they are going to be vastly different anyway.

Hence node-fetch, minimal code for a window.fetch compatible API on Node.js runtime.

Features

  • Stay consistent with window.fetch API.
  • Make conscious trade-off when following whatwg fetch spec and stream spec implementation details, document known difference.
  • Use native promise, but allow substituting it with [insert your favorite
  • promise library].
  • Use WhatWG ReadableStream for streaming bodies, on both request and response.
  • Useful extensions such as timeout, redirect limit, response size limit, explicit reject errors.

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!

Install

npm install node-fetch-polyfill --save

Usage

var fetch = require('node-fetch-polyfill');

// If you are not on node v0.12, set a Promise library first, eg.
// fetch.Promise = require('bluebird');

// plain text or html

fetch('https://github.com/')
    .then(function(res) {
        return res.text();
    }).then(function(body) {
        console.log(body);
    });

// json

fetch('https://api.github.com/users/github')
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

// meta

fetch('https://github.com/')
    .then(function(res) {
        console.log(res.ok);
        console.log(res.status);
        console.log(res.statusText);
        console.log(res.headers.raw());
        console.log(res.headers.get('content-type'));
    });

// post

fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

// post with stream from resumer

var resumer = require('resumer');
var stream = resumer().queue('a=1').end();
fetch('http://httpbin.org/post', { method: 'POST', body: stream })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

// post with form-data (detect multipart)

var FormData = require('form-data');
var form = new FormData();
form.append('a', 1);
fetch('http://httpbin.org/post', { method: 'POST', body: form })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

// post with form-data (custom headers)

var FormData = require('form-data');
var form = new FormData();
form.append('a', 1);
fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
    .then(function(res) {
        return res.json();
    }).then(function(json) {
        console.log(json);
    });

// node 0.11+, yield with co

var co = require('co');
co(function *() {
    var res = yield fetch('https://api.github.com/users/github');
    var json = yield res.json();
    console.log(res);
});

See test cases for more examples.

API

fetch(url, options)

Returns a Promise

Url

Should be an absolute url, eg http://example.com/

Options

default values are shown, note that only method, headers, redirect and body are allowed in window.fetch, others are node.js extensions.

{
    method: 'GET'
    , headers: {}        // request header. format {a:'1'} or {b:['1','2','3']}
    , redirect: 'follow' // set to 'manual' to extract redirect headers, `error` to reject redirect
    , follow: 20         // maximum redirect count. 0 to not follow redirect
    , timeout: 0         // req/res timeout in ms. 0 to disable (os limit still applies), timeout reset on redirect
    , compress: true     // support gzip/deflate content encoding. false to disable
    , size: 0            // maximum response body size in bytes. 0 to disable
    , body: empty        // request body. can be a string, buffer, readable stream
    , agent: null        // http.Agent instance, allows custom proxy, certificate etc.
}

License

MIT

Acknowledgement

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

changelog

Changelog

1.x release

v1.5.3 (master)

  • Fix: handles 204 and 304 responses when body is empty but content-encoding is gzip/deflate
  • Fix: allow resolving response and cloned response in any order
  • Fix: avoid setting content-length when form-data body use streams
  • Fix: send DELETE request with content-length when body is present
  • Fix: allow any url when calling new Request, but still reject non-http(s) url in fetch

v1.5.2

  • Fix: allow node.js core to handle keep-alive connection pool when passing a custom agent

v1.5.1

  • Fix: redirect mode manual should work even when there is no redirection or broken redirection

v1.5.0

  • Enhance: rejected promise now use custom Error (thx to @pekeler)
  • Enhance: FetchError contains err.type and err.code, allows for better error handling (thx to @pekeler)
  • Enhance: basic support for redirect mode manual and error, allows for location header extraction (thx to @jimmywarting for the initial PR)

v1.4.1

  • Fix: wrapping Request instance with FormData body again should preserve the body as-is

v1.4.0

  • Enhance: Request and Response now have clone method (thx to @kirill-konshin for the initial PR)
  • Enhance: Request and Response now have proper string and buffer body support (thx to @kirill-konshin)
  • Enhance: Body constructor has been refactored out (thx to @kirill-konshin)
  • Enhance: Headers now has forEach method (thx to @tricoder42)
  • Enhance: back to 100% code coverage
  • Fix: better form-data support (thx to @item4)
  • Fix: better character encoding detection under chunked encoding (thx to @dsuket for the initial PR)

v1.3.3

  • Fix: make sure Content-Length header is set when body is string for POST/PUT/PATCH requests
  • Fix: handle body stream error, for cases such as incorrect Content-Encoding header
  • Fix: when following certain redirects, use GET on subsequent request per Fetch Spec
  • Fix: Request and Response constructors now parse headers input using Headers

v1.3.2

  • Enhance: allow auto detect of form-data input (no FormData spec on node.js, this is form-data specific feature)

v1.3.1

  • Enhance: allow custom host header to be set (server-side only feature, as it's a forbidden header on client-side)

v1.3.0

  • Enhance: now fetch.Request is exposed as well

v1.2.1

  • Enhance: Headers now normalized Number value to String, prevent common mistakes

v1.2.0

  • Enhance: now fetch.Headers and fetch.Response are exposed, making testing easier

v1.1.2

  • Fix: Headers should only support String and Array properties, and ignore others

v1.1.1

  • Enhance: now req.headers accept both plain object and Headers instance

v1.1.0

  • Enhance: timeout now also applies to response body (in case of slow response)
  • Fix: timeout is now cleared properly when fetch is done/has failed

v1.0.6

  • Fix: less greedy content-type charset matching

v1.0.5

  • Fix: when follow = 0, fetch should not follow redirect
  • Enhance: update tests for better coverage
  • Enhance: code formatting
  • Enhance: clean up doc

v1.0.4

  • Enhance: test iojs support
  • Enhance: timeout attached to socket event only fire once per redirect

v1.0.3

  • Fix: response size limit should reject large chunk
  • Enhance: added character encoding detection for xml, such as rss/atom feed (encoding in DTD)

v1.0.2

  • Fix: added res.ok per spec change

v1.0.0

  • Enhance: better test coverage and doc

0.x release

v0.1

  • Major: initial public release