Skip to content
πŸ”₯ Cross-Browser HTTP client
Branch: master
Clone or download

README.md

min+gzip size min size flow-typed npm version
libraries.io

cb-fetch

A truly cross-browser and forward-compatible library to do asynchronous HTTP requests that follows the callback pattern.

Table of Contents

Installation

npm

npm install --save cb-fetch

yarn

yarn add cb-fetch

jspm

jspm install cb-fetch

bower

bower install --save cb-fetch#master

jsDelivr

<script src="//cdn.jsdelivr.net/combine/npm/@string/isstring/isString.min.js,npm/cb-fetch/index.min.js" type="text/javascript"></script>

Features

Importation

AMD

  define(function (require) {
    var request = require('cb-fetch');
  });
  
CJS

standard compliant


  var request = require('cb-fetch')['default'];
  

Node.js compatible


  var request = require('cb-fetch');
  
YUI

  YUI({
    modules: { 'is-string': 'path/to/@string/isstring.js' }
  }).use('is-string', 'cb-fetch', function (Y) {
    var request = Y['default'];
  });
  
TS

  import request = require('cb-fetch');
  
Global Namespace

If none of the previously listed module registration methods are supported, a global variable named request will be exposed.

Examples

// here's your typical request
request('http://www.example.com?key1=value1&key2=value2')
  .done(response => { /* … */ });

// taking a comprehensive approach is encouraged though
request()
  .get('http://www.example.com')
  .query('key1=value1&key2=value2')
  .done(onSuccessCallback, onErrorCallback);

// passing an object offers options not available otherwise
let json = request({
  url:          new URL('http://www.example.com'),
  parameters:   new URLSearchParams('_csrf=TOKEN'),
  mode:         'cors',
  credentials:  'include',
  responseType: 'json',
  headers:      { 'Content-Type': 'application/json' }
});

// let's put that base config to good use
let abort = json.get('/segment')
                .query({ foo: ['bar', 'qux'] })
                .hook('download', e => { /* … */ })
                .done({
                    success: onSuccessCallback,
                    error:   onErrorCallback,
                    abort:   onAbortCallback
                });

// forcefully aborts the request
abort();

API

Map

(?: Options | Options.url)
=> Object ┬─────────────────○ done
          β”œβ”€β”€β”€β”€β”€β”€β— hookⁿ ───○ done
          β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”
          β”œβ”€β”€β”€ get    β”‚
          β”‚  β”‚ head   β”‚
          β”‚  β”‚ delete β”‚
          β”‚  β””β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
          β”‚    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β—‹ done
          β”‚    β”œβ”€β— hookⁿ ───○ done
          β”‚    └─● query ───○ done
          β”‚      └─● hookⁿ ─○ done
          β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”
          └─── patch β”‚
             β”‚ post  β”‚
             β”‚ put   β”‚
             β””β”€β”¬β”€β”€β”€β”€β”€β”˜
               β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β—‹ done
               β”œβ”€β— hookⁿ ───○ done
               └─● send ────○ done
                 └─● hookⁿ ─○ done

Method Signatures

HTTP verbs

(Options.url) => Object

query

(Options.parameters) => Object

send

(Options.body) => Object

hook

loadstart
('loadstart', () => Boolean | Void) => Object
download
('download', (Object) => Any) => Object
loadend
('loadend', () => Any) => Object

done

{
  (onSuccess?: Function, onError?: Function),
  ({
    success?:  Function,
    error?:    Function,
    timeout?:  Function,
    abort?:    Function
  })
} => () => Void,
  throws: TypeError

Properties

Request Options

Property Default Value(s)
body null BufferSource, Blob, DocumentΒ², FormData, String, URLSearchParams, ReadableStream
credentials 'same‑origin' 'include', 'omit'⁢, 'same-origin'
headers {} Object, HeadersΒ³
method 'GET' String
mode 'same‑origin' 'cors', 'no-cors'ΒΉ, 'same-origin'
password null String
parameters URLSearchParams, Object, String
responseMediaTypeΒ² String
responseType 'text', 'json', 'blob', 'document', 'arraybuffer', 'formdata'ΒΉ, 'moz-blob', 'moz-chunked-arraybuffer', 'moz-chunked-text', 'msxml-document'
timeout 0 β„•
username null String
url location.href String, URL
multipart⁷ false Boolean
tunneling⁡ false Boolean
XSLPattern⁴ false Boolean

Progress Event

Property Type
chunk String, ArrayBuffer, Blob, Uint8Array, null
aggregate String, ArrayBuffer, Blob, Uint8Array, null
loaded β„•
total β„•
lengthComputable Boolean

Response

Property Type
body Object, String, Document, ArrayBuffer, Blob, FormDataΒΉ, ReadableStreamΒΉ, null
headers Object
instance XMLHttpRequest, XDomainRequest, Response, AnonXMLHttpRequest
statusCode β„•
statusText String
url String

ΒΉ fetch only
Β² XHR only
Β³ except Firefox 34–43
⁴ MSXML 3.0 only
⁡ method override
⁢ fetch, Firefox 16+, Presto/2.10.232–2.12.423
⁷ Gecko 1.7β–22

Gotchas

delete reserved keyword

In pre-ES5 environments, the delete method requires the use of the bracket notation.

Gecko

For the browsers powered by Gecko ≀20 to have the exposed response headers populated into the headers property, the following conditions must be met:

  • Access-Control-Expose-Headers response header exposes itself
  • Access-Control-Expose-Headers field value is not *
  • mode set to cors

Trident

XDomainRequest intrinsic limitations

  • only support GET and POST methods
  • cannot set request headers
  • no credentials
  • same scheme restriction
  • the informational and redirection status code classes are considered errors
  • the response's status code and status text are not supplied
  • same-origin requests also requires the server to respond with an Access-Control-Allow-Origin header of either * or the exact URL of the requesting document

Platform for Privacy Preferences

Internet Explorer’s default settings restrict the use of 3rd party cookies unless a P3P compact policy declaration has been included through a custom HTTP response header; hence, the "include" credentials mode cannot be fully honored if a cookie has been deemed unsatisfactory.

License

FOSSA Status

You can’t perform that action at this time.