Detalhes do pacote

cb-fetch

Mouvedia40MIT1.10.0

Normalize fetch, XMLHttpRequest and XDomainRequest using an easy-to-use API

fetch, XHR, XMLHttpRequest, XDR

readme (leia-me)

min+gzip size min size Flow TypeScript 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

<summary>AMD</summary>

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

standard compliant


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

Node.js compatible


  var request = require('cb-fetch');
  
<summary>YUI</summary>

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

  import request = require('cb-fetch');
  
<summary>Global Namespace</summary>

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 abort = request({
  url:          new URL('http://www.example.com'),
  parameters:   new URLSearchParams('_csrf=TOKEN'),
  mode:         'cors',
  credentials:  'include',
  responseType: 'json',
  headers:      { 'Content-Type': 'application/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 Gecko 34–43
⁴ MSXML 3.0 only
⁵ method override
⁶ fetch, Gecko 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 1.9.1–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 require 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

changelog (log de mudanças)

Change Log

1.10.0 - 2019-06-10

Fixed

  • Firefox 3.5–7 support in the context of a web worker
  • Firefox 3.6 handles empty 304 response
  • match the document's MIME type to a parameter-less Content-Type header
  • URL
    • extract credentials in a cross-browser manner
    • strip the credentials

Added

  • TypeScript declaration file
  • Flow library definition
  • Bower manifest
  • fetch
    • timeout callback
    • timeout option

Changed

  • verb methods accept paths as argument
  • the query method appends
  • optimized index.min.js parsing
  • plain object parameters serialization
    • array support
    • undefined properties get skipped
    • null properties emulate name="isindex"
  • fetch
    • invalid JSON throws
    • abort becomes a no-op after completion

Removed

  • caching option

Security

  • the ProhibitDTD second-level XML DOM property is explicitly set to false

1.5.0 - 2018-09-25

Fixed

  • Internet Explorer 10+ support in the context of a web worker
  • XDR Content-Type header is set in a timely manner

Added

  • jspm shortname
  • hooks
  • cancellation
  • download monitoring
  • XHR
    • timeout fallback
    • multipart option
    • caching option

Changed

  • 'msxml-document' responseType falls back to 'document' if not supported
  • 'omit' credentials mode support for older versions of Firefox and Opera
  • advanced settings were folded into the options
  • restrict the non-standard response types to XHR
  • success callback is optional
  • if AMD is the chosen format, String.isString's module ID must be '@string/isstring'

Removed

  • mozSystem flag support
  • undocumented signal option

1.0.0 - 2018-05-10

Final Release

  • normalized handling of credentials
  • handle obsolete line folding during parsing of HTTP header field values
  • support line feed as a line terminator
  • all exceptions thrown while extracting exposed headers are now swallowed
  • work around XDR same scheme restriction

Release Candidate 2

  • consistent handling of invalid JSON
  • options and the processed response are now properly reset during the init phase

Release Candidate 1

  • WebDAV optimizations
  • verb tunneling using custom HTTP header fields
  • proper handling of XML parsing errors
  • the headers property is now automatically populated with the exposed headers listed in the Access-Control-Expose-Headers HTTP response header

Beta 2

  • XDR
  • timeout callback
  • automatic document parsing
  • XSL pattern query language option for Trident-based browsers
  • response normalization
  • YUI module
  • XHR constructor parameter support for Gecko-powered browsers

0.9.0-alpha.4–9

  • automatically extract credentials from the URL
  • ; separator for the Cookie HTTP header field value in accordance with RFC 2109
  • URL instance support
  • polymorphic done method