• Stars
    star
    804
  • Rank 56,681 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A small xhr wrapper

xhr

Join the chat at https://gitter.im/naugtur-xhr/Lobby

A small XMLHttpRequest wrapper. Designed for use with browserify, webpack etc.

API is a subset of request so you can write code that works in both node.js and the browser by using require('request') in your code and telling your browser bundler to load xhr instead of request.

For browserify, add a browser field to your package.json:

"browser": {
  "request": "xhr"
}

For webpack, add a resolve.alias field to your configuration:

"resolve": {
  "alias": {
    "request$": "xhr"
  }
}

Browser support: IE8+ and everything else.

Installation

npm install xhr

Example

var xhr = require("xhr")

xhr({
    method: "post",
    body: someJSONString,
    uri: "/foo",
    headers: {
        "Content-Type": "application/json"
    }
}, function (err, resp, body) {
    // check resp.statusCode
})

var req = xhr(options, callback)

type XhrOptions = String | {
    useXDR: Boolean?,
    sync: Boolean?,
    uri: String,
    url: String,
    method: String?,
    timeout: Number?,
    headers: Object?,
    body: String? | Object?,
    json: Boolean? | Object?,
    username: String?,
    password: String?,
    withCredentials: Boolean?,
    responseType: String?,
    beforeSend: Function?
}
xhr := (XhrOptions, Callback<Response>) => Request

the returned object is either an XMLHttpRequest instance or an XDomainRequest instance (if on IE8/IE9 && options.useXDR is set to true)

Your callback will be called once with the arguments ( Error, response , body ) where the response is an object:

{
    body: Object||String,
    statusCode: Number,
    method: String,
    headers: {},
    url: String,
    rawRequest: xhr
}

Your callback will be called with an Error if there is an error in the browser that prevents sending the request. A HTTP 500 response is not going to cause an error to be returned.

Other signatures

  • var req = xhr(url, callback) - a simple string instead of the options. In this case, a GET request will be made to that url.

  • var req = xhr(url, options, callback) - the above may also be called with the standard set of options.

Convience methods

  • var req = xhr.{post, put, patch, del, head, get}(url, callback)
  • var req = xhr.{post, put, patch, del, head, get}(options, callback)
  • var req = xhr.{post, put, patch, del, head, get}(url, options, callback)

The xhr module has convience functions attached that will make requests with the given method. Each function is named after its method, with the exception of DELETE which is called xhr.del for compatibility.

The method shorthands may be combined with the url-first form of xhr for succinct and descriptive requests. For example,

xhr.post('/post-to-me', function(err, resp) {
  console.log(resp.body)
})

or

xhr.del('/delete-me', { headers: { my: 'auth' } }, function (err, resp) {
  console.log(resp.statusCode);
})

Options

options.method

Specify the method the XMLHttpRequest should be opened with. Passed to XMLHttpRequest.open. Defaults to "GET"

options.useXDR

Specify whether this is a cross origin (CORS) request for IE<10. Switches IE to use XDomainRequest instead of XMLHttpRequest. Ignored in other browsers.

Note that headers cannot be set on an XDomainRequest instance.

options.sync

Specify whether this is a synchrounous request. Note that when this is true the callback will be called synchronously. In most cases this option should not be used. Only use if you know what you are doing!

options.body

Pass in body to be send across the XMLHttpRequest. Generally should be a string. But anything that's valid as a parameter to XMLHttpRequest.send should work (Buffer for file, etc.).

If options.json is true, then this must be a JSON-serializable object. options.body is passed to JSON.stringify and sent.

options.uri or options.url

The uri to send a request to. Passed to XMLHttpRequest.open. options.url and options.uri are aliases for each other.

options.headers

An object of headers that should be set on the request. The key, value pair is passed to XMLHttpRequest.setRequestHeader

options.timeout

Number of miliseconds to wait for response. Defaults to 0 (no timeout). Ignored when options.sync is true.

options.json

Set to true to send request as application/json (see options.body) and parse response from JSON.

For backwards compatibility options.json can also be a valid JSON-serializable value to be sent to the server. Additionally the response body is still parsed as JSON

For sending booleans as JSON body see FAQ

options.withCredentials

Specify whether user credentials are to be included in a cross-origin request. Sets XMLHttpRequest.withCredentials. Defaults to false.

A wildcard * cannot be used in the Access-Control-Allow-Origin header when withCredentials is true. The header needs to specify your origin explicitly or browser will abort the request.

options.responseType

Determines the data type of the response. Sets XMLHttpRequest.responseType. For example, a responseType of document will return a parsed Document object as the response.body for an XML resource.

options.beforeSend

A function being called right before the send method of the XMLHttpRequest or XDomainRequest instance is called. The XMLHttpRequest or XDomainRequest instance is passed as an argument.

options.xhr

Pass an XMLHttpRequest object (or something that acts like one) to use instead of constructing a new one using the XMLHttpRequest or XDomainRequest constructors. Useful for testing.

FAQ

  • Why is my server's JSON response not parsed? I returned the right content-type.
    • See options.json - you can set it to true on a GET request to tell xhr to parse the response body.
    • Without options.json body is returned as-is (a string or when responseType is set and the browser supports it - a result of parsing JSON or XML)
  • How do I send an object or array as POST body?
    • options.body should be a string. You need to serialize your object before passing to xhr for sending.
    • To serialize to JSON you can use options.json:true with options.body for convenience - then xhr will do the serialization and set content-type accordingly.
  • Where's stream API? .pipe() etc.
    • Not implemented. You can't reasonably have that in the browser.
  • Why can't I send "true" as body by passing it as options.json anymore?
    • Accepting true as a value was a bug. Despite what JSON.stringify does, the string "true" is not valid JSON. If you're sending booleans as JSON, please consider wrapping them in an object or array to save yourself from more trouble in the future. To bring back the old behavior, hardcode options.json to true and set options.body to your boolean value.
  • How do I add an onprogress listener?
    • use beforeSend function for non-standard things that are browser specific. In this case:
    xhr({
      ...
      beforeSend: function(xhrObject){
        xhrObject.onprogress = function(){}
      }
    })

Mocking Requests

You can override the constructor used to create new requests for testing. When you're making a new request:

xhr({ xhr: new MockXMLHttpRequest() })

or you can override the constructors used to create requests at the module level:

xhr.XMLHttpRequest = MockXMLHttpRequest
xhr.XDomainRequest = MockXDomainRequest

MIT Licenced

More Repositories

1

blocked-at

Detects node eventloop block and reports where it started
JavaScript
319
star
2

insertionQuery

Non-dom-event way to catch nodes showing up. And it uses selectors.
JavaScript
190
star
3

npm-audit-resolver

JavaScript
121
star
4

node-example-flamegraph

Shell
66
star
5

can-i-ignore-scripts

JavaScript
56
star
6

debugging-aid

Experimental tools for debugging Node.js apps without pausing
JavaScript
54
star
7

builder4impress

A tool to build slides in impress.js in a WYSIWYG manner
JavaScript
36
star
8

node-diagnostics-howtos

23
star
9

handsfreeyoutube

no hands and no eyes youtube experience
JavaScript
23
star
10

backbone-redux-migrator

Lets Backbone and Redux apps coexist, so you don't have to rewrite everything at once
JavaScript
23
star
11

https-proxy-cli

One command to run a local https server proxying to local http
JavaScript
20
star
12

naughty-images

SVG Images with XSS in them
C
17
star
13

safe-memory-cache

Secure and size-limited in-memory cache for node.js
JavaScript
14
star
14

node-example-heapdump

JavaScript
14
star
15

js-training-examples

Examples for JS trainings
JavaScript
13
star
16

CSP-exercise

JavaScript
12
star
17

strongly-typed

Strongly typed javascript objects, self-validating, detailed error reports
JavaScript
11
star
18

aframe-point-component

implements a-point based on THREE.js point object
JavaScript
11
star
19

naugtur.github.com

HTML
9
star
20

overlord.js

Mediator pattern taken to the limits. Can do more than just PubSub
JavaScript
9
star
21

secure-dependencies

Creates a tarball of your app dependencies checked with node security platform
JavaScript
8
star
22

lavalab

JavaScript
8
star
23

google-pubsub-mock

Transparently overrides @googlecloud/pub-sub for local testing
JavaScript
8
star
24

ripper

Ripper.js - copy fragments of DOM and insert to another document preserving the CSS styles of elements
JavaScript
8
star
25

jQuery-Mobile-dictionary

Community jquerymobile documentation in a handy form
JavaScript
8
star
26

meetjs.pl

Official meet.js website
TypeScript
5
star
27

node-examples

examples for node trainings
HTML
4
star
28

axons.js

A communication channel you always wanted instead of pub-sub
JavaScript
4
star
29

extendable-module

Extendable Revealing Module - lets you extend the private parts [ seriously ;) ]
JavaScript
4
star
30

research

Rabbit-holes and wild-goose chases.
JavaScript
3
star
31

git-livecoding

a tool to show commits from history as if they were about to be made
Shell
3
star
32

promise-blocked

Detect which function blocks your eventloop
JavaScript
3
star
33

human-redux-reactor

JavaScript
3
star
34

transitionrunner

tiny bit of javascript enabling CSS-defined animations with fallback for older browsers
JavaScript
3
star
35

csp-report-lite

JavaScript
3
star
36

selfexplanatory.js

Make your functions and methods self-explanatory with this simple wrapper
JavaScript
3
star
37

request-dependency

Requesting dependencies instead of DI
JavaScript
2
star
38

selfaware

A bind function for all the methods at once
JavaScript
2
star
39

package-firewall

An experimental package network access control tool
JavaScript
2
star
40

audit-resolve-core

Core modules for audit-resolve.json file and logic of its processing
JavaScript
1
star
41

js-memory-demo

Simple tests demonstrating memory impact of certain bits of code
JavaScript
1
star
42

alphabet-game

HTML
1
star
43

training-notes

HTML
1
star
44

podcastmaker-cli

a pile of bash tricks for unattended audio editing
Shell
1
star
45

node-example-websec

Example app for learning websecurity fundamentals
HTML
1
star
46

redux-request-generator

no-boilerplate http requests from redux apps
JavaScript
1
star
47

i-run-code-from-the-internet

1
star
48

debugging-tools-livecoding

1
star
49

bootstrap-prototyping

tiny introduction to prototyping with bootstrap - for UX designers
CSS
1
star
50

aframe-livereload-image

JavaScript
1
star