@edgeguideab/client-request

Wrapper around the XMLHttpRequest object for easier promise-based ajax requests

Stats

StarsIssuesVersionUpdatedCreatedSize
@edgeguideab/client-request
1.7.0a month ago4 years agoMinified + gzip package size for @edgeguideab/client-request in KB

Readme

Install via NPM

npm install @edgeguideab/client-request

In the browser

You will need to require the module and then package your scripts using a bundler like webpack or browserify.

Supported HTTP methods

Name
GET
HEAD
DELETE
POST
PUT
PATCH

Usage

make GET promise requests

const request = require('@edgeguideab/client-request');

request.get('http://mydummypage.xxc')
  .then(r => {
    console.log(r);
    // { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);
    // { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

All status codes >= 400 will cause a rejection, otherwise the promise will resolve.

GET requests with a query string

const request = require('@edgeguideab/client-request');

request.get('http://mydummypage.vvv?foo=bar&biz=buzz')
  .then(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

GET requests with options

const request = require('@edgeguideab/client-request');

request.get('http://mydummypage.vvv', {
  headers: {
    'Accept': 'application/json'
  },
  query: {
    'dead': 'beef'
  },
  withCredentials: false, //default is true
  timeout: 10000 //Timeout for the request in milliseconds
}).then(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

Headers can be set using the options object. You can provide an object containing key/value pairs instead of a query string. The above will send a GET request to http://mydummypage.vvv?dead=beef. We recommend using the object approach when the keys/values contain characters that need url encoding, since this will be done by the module.

DELETE requests with options

const request = require('@edgeguideab/client-request');

request.delete('http://mydummypage.vvv', {
  headers: {
    'Accept': 'application/json'
  },
  query: {
    'dead': 'beef'
  },
  withCredentials: false, //default is true
  timeout: 10000 //Timeout for the request in milliseconds
}).then(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

The delete function works in the same way as the GET function.

POST requests

const request = require('@edgeguideab/client-request');
let form = new FormData();
let input = document.querySelector('input[type="file"]');
form.set('dead', 'beef');
form.set('file', input.files[0]);

request.post('http://mydummypage.vvv', {
  body: form,
  timeout: 10000 //Timeout for the request in milliseconds
}).then(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

Just like in get requests, the data is send in the options object under the key "data". Note that unlike GET and DELETE, methods with a body like PUT, POST and PATCH can have different values than JSON as their data, like FormData or plain text.

const request = require('@edgeguideab/client-request');

request.post('http://mydummypage.vvv', {
  body: {
    dead: 'beef'
  },
  timeout: 10000 //Timeout for the request in milliseconds
}).then(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);// { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

You can of course just send JSON data. The content type will be "application/json" if you send an array or plain object without specifying another content-type in the headers object. For all other data, the content type will be left to the XMLHttpRequest to decide unless specified.

Options (DELETE/GET/HEAD)

Name Type Description
query Object Key/value pair of query string arguments. {dead: 'beef' } will be interpreted as dead=beef in the url
timeout int The time in milliseconds before the request times out. The default is 60000 (1 min)
headers object Key/value pair of all the request headers.
withCredentials Boolean Determines whether cookies should be sent along or not. The default is true
onDataReceived Function Will be called each time data is received. It will send along an object { event: Object, loaded: dataLoaded, total: totalDataToBeSent } containing the original event from the XMLHttpRequest, the data received so far and the total data to be received
handle int this is an identifier which is used as input to the getRequestObject or abortRequest functions. It should be generated with generateRequestHandle to ensure that it's unique. It can be used to retrieve the internal XMLHttpRequest object for a certain request with the particular handle id

Options (POST/PUT/PATCH)

Name Type Description
query Object Key/value pair of query string arguments. {dead: 'beef' } will be interpreted as dead=beef in the url
body Object The request body. This can be anything, but the content-type will only be set automatically for plain objects and arrays. If the data is something other than these types and no content-type header is provided, the content type will be decided by the XMLHttpRequest object
timeout int The time in milliseconds before the request times out. The default is 60000 (1 min)
headers object Key/value pair of all the request headers.
withCredentials Boolean Determines whether cookies should be sent along or not. The default is true
onDataUploaded Function Will be called each time data is uploaded. It will send along an object { event: Object, loaded: dataLoaded, total: totalDataToBeSent } containing the original event from the XMLHttpRequest, the data uploaded so far and the total data to be uploaded
onDataReceived Function Will be called each time data is received. It will send along an object { event: Object, loaded: dataLoaded, total: totalDataToBeSent } containing the original event from the XMLHttpRequest, the data received so far and the total data to be received
handle int this is an identifier which is used as input to the getRequestObject or abortRequest functions. It should be generated with generateRequestHandle to ensure that it's unique. It can be used to retrieve the internal XMLHttpRequest object for a certain request with the particular handle id

Aborting requests

const request = require('@edgeguideab/client-request');
const handle = request.generateRequestHandle();

request.get('http://mydummypage.xxc', { handle })
  .then(r => {
    console.log(r);
    // { event: Object, originalObject: XMLHttpRequest, status: 200, data: String/Object, size: oEvent.total }
  });
  .catch(r => {
    console.log(r);
    // { event: Object, originalObject: XMLHttpRequest, status: 400, error: String/Object }
  });

const xmlHttpRequest = request.getRequestObject(handle);
xmlHttpRequest.abort();

// You can also use the shorthand
request.abortRequest(handle)

To abort a request, you need to access the internal XMLHttpRequest object and it's 'abort' function. First, generate a handle and pass it in the request options. After the request has been sent, you can use this handle to retrieve the native object or use the shorthand function to cancel the request.

Author

EdgeGuide AB

If you find any bugs or have a feature request, please open an issue on github!

The npm package download data comes from npm's download counts api and package details come from npms.io.