Fetchify
Fetchify is a fork of Github's window.fetch polyfill
It is adapted to be used primarily within Node as part of a Browserify bundle. It is also tested and pluggable with various Promise implementations such as Bluebird and Q
window.fetch polyfill
The global fetch
function is an easier way to make web requests and handle
responses than using an XMLHttpRequest. This polyfill is written as closely as
possible to the standard Fetch specification at https://fetch.spec.whatwg.org.
Installation
Install with npm
.
$ npm install fetchify --save
Usage
The fetch
function supports any HTTP method. We'll focus on GET and POST
example requests.
Node
Example using Bluebird
var Promise = ; var fetch = Promisefetch; //Headers, Request and Response are also exportedvar Headers = PromiseHeaders;var Request = PromiseRequest;var Response = PromiseResponse;
You could also use Q
var Promise = Promise; var fetch = Promisefetch;
In the browser
Fetchify also provides a browser polyfill build (see the dist
directory).
If you don't want to globally polyfill a Promise impl, you can also inject it:
More examples
JSON
Response metadata
Post form
var form = document
Post JSON
File upload
var input = document var form = formform
Success and error handlers
This causes fetch
to behave like jQuery's $.ajax
by rejecting the Promise
on HTTP failure status codes like 404, 500, etc. The response Promise
is
resolved only on successful, 200 level, status codes.
{ if responsestatus >= 200 && responsestatus < 300 return Promise else return Promise } { return response}
Browser Support
Latest ✔ | Latest ✔ | 10+ ✔ | Latest ✔ | 6.1+ ✔ |