XHR Service

The XhrService offers APIs to manage HTTP requests with Promise.

Features

The XhrService offers:

  • a flexible request method wrapping the native XMLHttpRequest,
  • shortcut methods for get, post, put, patch, del and head,
  • feature detection and partial polyfill for XMLHttpRequest.requestType,
  • convenience methods to build RFC compliant requests (query-string, form-urlencoded, RFC3986, RFC5987),
  • wrappers around the API that default to whatever options you pass to them allowing multiple cascading defaults sets,
  • jQuery-style beforeSend callback to modify requests on-the-fly,
  • basic time statistics,
  • a serverDown event

Body options and defaults wrapper inspired by Node request

The generic request() method

This method is the center of it all. The other async methods are only shortcuts. See more examples below.

$XhrService.getInstance()
    .request('http://myserver.com/api/getSomeData', {
        method: 'GET',
        timeout: 30000
    })
    .then(function(request) {
        console.info('Server replied', request.response);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

Using default options

The $XhrService.getInstance().defaults(options) method returns a wrapper around the normal API that defaults to whatever options you pass to it.

Note

.defaults() does not modify the global request API. Instead, it returns a wrapper that has your default settings applied to it.

Note

You can call .defaults() on the wrapper that is returned from $XhrService.getInstance().defaults to add/override defaults that were previously set.

// Send requests with responseType: json
var myServer = $XhrService.getInstance().defaults({ responseType: 'json' });

myServer.get('http://myserver.com/get_some_data')
    .then(function(request) {
        // request.response is an object parsed from json
    });

// Send requests with responseType: json AND custom headers
var myServerAuth = myServer.defaults({
    headers: {
        Authorization: 'Bearer mF_9.B5f-4.1JqM',
        'x-connection-type': 'WIFI'
    },
})

myServerAuth.get('http://myserver.com/get_some_data_with_authentication')
    .then(function(request) {
        console.info('Server replied', request.response);
    });

The beforeSend callback.

beforeSend is a pre-request callback function that can be used to modify the XMLHTTPRequest object before it is sent. Use this to set custom headers, etc.

Note

Returning false in the beforeSend function will cancel the request.

var xhr = $XhrService.getInstance().defaults({
    responseType: 'json',
    timeout: 30000,
    beforeSend: function(url, xhr, conf) {
        if (!isLoggedIn || !accessToken) {
            throw new Error("Not logged in, can't send request.");
        }
        xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
    }
});
xhr.get('http://myserver.com').then(function(request) {
    console.info('Server replied', request.response);
});

Usage examples

The get, post, put, patch, head and del methods are convenient shortcuts to the request method.

Simple GET

$XhrService.getInstance()
    .get('http://myserver.com/api/getSomeData')
    .then(function(request) {
        console.info('Server replied', request.response);
        console.info('Status', request.status, request.statusText);
        console.info('Response headers', request.headers);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

GET with parameters

$XhrService.getInstance()
    .get('http://myserver.com/search', { contains: 'weather', sortby: 'date' })
    .then(function(request) {
        console.info('Server replied', request.response);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

Simple POST as JSON

$XhrService.getInstance()
    .post('http://myserver.com/get_article', { itemID: 123 })
    .then(function(request) {
        console.info('Server replied', request.response);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

Simple POST as x-www-form-urlencoded

$XhrService.getInstance()
    .post('http://myserver.com/get_article', null, { form: { itemID: 123 } })
    .then(function(request) {
        console.info('Server replied', request.response);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

POST an HTML form as multipart/formData

var myForm = document.getElementById('myform');
$XhrService.getInstance()
    .post('http://myserver.com/upload_data', null, { formData: myform })
    .then(function(request) {
        console.info('Server replied', request.response);
    }, function(error) {
        console.log(error.url ' returned status code ' + error.request.status);
    });

Using options

$XhrService.getInstance()
    .get('http://myserver.com/get_article', null, {
        headers: {
            Authorization: 'Bearer mF_9.B5f-4.1JqM',
            'x-connection-type': 'WIFI'
        },
        responseType: 'json'
    })
    .then(function(request) {
        console.info('Server replied', request.response);
    });