-
Notifications
You must be signed in to change notification settings - Fork 0
/
requests.js
46 lines (38 loc) · 916 Bytes
/
requests.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
* Request Utils
*/
let csrf;
function csrfToken() {
csrf = csrf || document.querySelector('meta[name=csrf-token]');
return csrf && csrf.content;
}
function fetchInternal(verb, endpoint, body, headers) {
const data = {
method: verb,
credentials: 'same-origin',
headers
};
if (body) {
body._method = verb;
data.body = JSON.stringify(body);
}
return fetch(endpoint, data);
}
export function fetchHtml(verb, endpoint, body) {
return fetchInternal(verb, endpoint, body, {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': csrfToken(),
});
}
export function fetchJson(verb, endpoint, body) {
return fetchInternal(verb, endpoint, body, {
'Content-Type': 'application/json',
'X-CSRF-Token': csrfToken(),
});
}
export function handleError(response) {
if (!response.ok) {
throw new Error('Received error from server');
}
return response;
}