ajax-promised
Simple ajax utility which returns a Promise. Automatically parses JSON response if response is application/json
. Serializes an Object of key/value pairs for easy query string creation in GET requests.
Checks HTTP status codes and rejects
unsuccessful requests for easy error handling.
Both resolve
and reject
recieve an Object containing:
{
data,
status,
xhr
}
Example usage:
import ajax from 'ajax-promised';
ajax({
url: '/api/users'
}).then(({ data, status, xhr }) => {
console.log('data', data);
console.log('status', status);
console.log('xhr', xhr);
});
ajax('/api/users').then(({ data }) => {
});
const { data } = await ajax({
url: '/api/users',
method: 'POST',
headers: {
'content-type': 'application/json'
},
data: JSON.stringify({
name: 'morpheus',
job: 'leader'
})
});
const { status } = await ajax({
url: '/api/users/2',
method: 'DELETE'
});
ajax({
url: '/path',
data: {
key: 'value',
key2: 'value2'
}
});
const { data } = await ajax({
url: '/path',
responseType: 'arraybuffer'
});
{
url: '',
method: 'GET',
cache: true,
headers,
data,
responseType,
withCredentials,
timeout,
onprogress
}