PicoAjax
Universal, very tiny (browser version is ~1kb uncompressed) yet fully functional AJAX library with zero dependencies. It implements browser XMLHttpRequest and Node.js http/https module returning Promise.
Motivation
What makes Pico-Ajax different is that it's unaware on how data is passed. That requires a few more bytes of code to make a request, but gives much more control and (more important) better understanding of HTTP requests in exchange. This also makes it perfect for building your own DIY API module.
Limitations
Since server implementation is mostly synchronous it's not recommended to use PicoAjax in loaded projects.
Install
Via npm:
npm install --save pico-ajax
then import pico-ajax module
import PicoAjax from 'pico-ajax';
const PicoAjax = require('pico-ajax');
Or use as a legacy module (will be available as PicoAjax in a global scope):
<script src="/scripts/picoajax.min.js"></script>
API
PicoAjax exposes all known http methods (connect, delete, get, head, options, patch, post and put) with two arguments: 'url' and 'options'.
First argument is url of type string. Note that you should compose GET parameters by yourself:
const params = new URLSearchParams({ foo: "bar", page: 2 }).toString();
const url = `https://example.com?${params}`;
PicoAjax
.get(url)
.then(response => console.log('response received'));
Second argument (options) is a plain object, whose keys override defaults below:
options: {
body: undefined,
headers: {},
password: undefined,
user: undefined,
timeout: undefined,
responseType: '',
async: true,
onProgress: undefined,
withCredentials: false,
}
PicoAjax http methods return Promises which are resolved with Response object:
response: {
body: any,
headers: Object,
statusCode: number,
statusMessage: string,
}
In case http didn't succeed (response code other than 2xx, or another error), Promise is rejected with an Error instance with reponse fields added:
error: {
name: string,
message: string,
body: any,
headers: Object,
statusCode: number,
statusMessage: string,
}
Usage
You may start right now with a simple GET request:
PicoAjax
.get('/some/api/?foo=bar&baz=qux')
.then(({ headers, body }) => {
console.log(headers, body);
})
.catch((error) => {
console.error(error.message, error.statusCode);
});
try {
const { headers, body } = await PicoAjax.get('/some/api/?foo=bar&baz=qux');
console.log(headers, body);
} catch (e) {
console.error(e.message, e.statusCode);
}
Multipart/form-data
const formData = new FormData(document.querySelector('form'));
const foo = { bar: 'baz' };
const formData = new FormData();
Object.keys(foo).forEach(key => {
formData.append(key, foo[key]);
});
PicoAjax
.post('/some/api/', { body: formData })
.then(({ headers, body, statusCode }) => {
console.log(statusCode, headers, body);
})
.catch((error) => {
console.error(error.message, error.statusCode);
});
JSON
const body = JSON.stringify({ foo: 'bar', baz: 'qux' });
const headers = { 'Content-Type': 'application/json' };
PicoAjax
.post('/some/api/', { body, headers })
.then(({ headers, body, statusCode }) => {
console.log(statusCode, headers, body);
})
.catch((error) => {
console.error(error.message, error.statusCode);
});
File upload
const formData = new FormData();
formData.append('userfile', fileInputElement.files[0]);
PicoAjax
.post('/some/api/', { body: formData })
.then(({ headers, body, statusCode }) => {
console.log(statusCode, headers, body);
})
.catch((error) => {
console.error(error.message, error.statusCode);
});
Advanced use
If you are going to make quite a few similar requests in your project, you probably
may want to make one more layer of abstraction over Pico-Ajax. Please refer to api-example.js
module in examples directory.
License
MIT found in LICENSE
file.