forked from jwarning/json-xhr-promise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
28 lines (23 loc) · 759 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
export default function (method, url, data) {
// create a promise around an xhr object with json
return new Promise((resolve, reject) => {
var request = new XMLHttpRequest();
request.open(method, url, true);
// support cross origin requests
request.setRequestHeader('Accept', '*/*');
request.setRequestHeader('Content-type', 'application/json');
request.withCredentials = true;
request.onload = () => {
if (request.status >= 200 && request.status < 300) {
resolve(JSON.parse(request.response));
}
else {
reject(Error(request.statusText));
}
};
request.onerror = () => {
reject(Error('A network error occurred'));
};
request.send(JSON.stringify(data));
});
}