xhr.js

1.0.2 • Public • Published

xhr.js

xhr.js is a library(< 2Kb) to make AJAX/HTTP restful requests with XMLHttpRequest. It has similar API with Python-requests.

Build Status npm npm npm

Usage

1. Install xhr.js

npm install xhr.js

2. import xhr.js

UMD import is supported, then get global object: XHR.

import XHR from 'xhr.js';
 
// or
 
var XHR = require("xhr.js");

or link with script in html files:

<script src="dist/xhr.min.js"></script>

3. use class XHR

var xhr = XHR(async); // default is async. you can set sync use  XHR(false)
xhr.on('success', function(result) {
    console.log('status_code:', result.status_code);
    console.log('status_text:', result.status_text);
    console.log('response_type:', result.response_type);
 
    console.log('text:', result.text);
    console.log('headers:', result.headers());
    console.log('json:', result.json()); // get the json result.
    console.log('xml:', result.xml());
});
 
xhr.get('package.json', params={'a': 'b'});

Detail API

1. XHR API

  1. xhr.request(method, url, body, onsuccess, onfail): request the url, with the method.
  2. xhr.on(): bind the request result(ready, error, success, fail), with result instance as it input.
  3. xhr.get(url, params, onsuccess, onfail): get request.
  4. xhr.post(url, params, onsuccess, onfail): post request.
  5. xhr.setRequestHeader(header_name, header_value): append a header.
  6. xhr.setAsync(aysnc): set request async / sync.
  7. xhr.url(): get the request url.
  8. xhr.body(): get the request body.
  9. xhr.abort(): abort request.
  10. xhr.reset(): reset the xhr instance, such url, headers, body, events.

2. XHR Event

  1. ready: when xhr is ready.
  2. error: when xhr can not be ready.
  3. success: when status_code is 200.
  4. fail: when status_code is not 200.

3. Response API (result)

  1. result.text: get all response text;
  2. result.status_code: the server response code;
  3. result.status_text: the server response code text, e.g. ok (status code is 200).
  4. result.response_type: response type;
  5. result.json: get the json object of response text;
  6. result.xml: get the xml object of response text;
  7. result.headers: get all the response headers object;

TODO

  • request auth
  • delete, put
  • a http test chrome plugin, like postman.

LICENSE

MIT

Package Sidebar

Install

npm i xhr.js

Weekly Downloads

0

Version

1.0.2

License

MIT

Last publish

Collaborators

  • atool