Giter Club home page Giter Club logo

cb-fetch's Introduction

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

Usage

Installation

npm

npm install --save cb-fetch

yarn

yarn add cb-fetch

jspm

jspm install cb-fetch

bower

bower install --save cb-fetch

jsDelivr

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

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 abort = request({
  url:          new URL('http://www.example.com'),
  parameters:   new URLSearchParams('_csrf=TOKEN'),
  mode:         'cors',
  credentials:  'include',
  responseType: 'json'
}).get('/segment')
  .query({ foo: ['bar', 'qux'] })
  .pass('Content-Type', 'application/json')
  .hook('download', e => { /* ā€¦ */ })
  .done({
    success: onSuccessCallback,
    error:   onErrorCallback,
    abort:   onAbortCallback
  });

// forcefully aborts the request
abort();

Support

  • fetch
  • XMLHttpRequest
  • XDomainRequest
  • Universal Module Definition
  • WebDAV
  • TypeScript
  • Flow

Methods

get / head / delete / post / patch / put

(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

pass

{
  (name: String, value: String),
  (headers: Object | Headers)
} => Object
  // assigns
  .pass(new Headers({ key: 'value' }))

  // appends
  .pass({ key: 'value' })

  // sets
  .pass('key', 'value')

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

cb-fetch's People

Contributors

mouvedia avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

fossabot

cb-fetch's Issues

add fetch-specific request options

redirect: "follow" | "error" | "manual"
referrer: "no-referrer" | "client" | URL
referrerPolicy: "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url"
integrity: String
keepalive: Boolean

cache will be covered by #4

abort

https://stackoverflow.com/questions/31061838
https://developers.google.com/web/updates/2017/09/abortable-fetch
https://www.quirksmode.org/blog/archives/2005/09/xmlhttp_notes_a_1.html
web-platform-tests/wpt#6484 (comment)
JakeChampion/fetch@da07fa1
https://lists.w3.org/Archives/Public/public-webapps/2013JanMar/0545.html
!!self.Request && 'signal' in self.Request.prototype

It is not really correct to manually force a connection to go away by nulling out various
aspects of the request object or callback function or overwriting an existing XHR with another
request. It may have a similar feeling to the end user in some cases because a callback wonā€™t
happen, but any changes may still happen on the server as the request, once sent, still happened.

P3P circumvention

on method

(event: String, handler: Function) => Object

CDN

jsDelivr

https://cdn.jsdelivr.net/combine/npm/@string/isstring/isString.min.js,npm/cb-fetch/index.min.js

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    šŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. šŸ“ŠšŸ“ˆšŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ā¤ļø Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.