-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhttpClient.js
More file actions
24 lines (24 loc) · 938 Bytes
/
httpClient.js
File metadata and controls
24 lines (24 loc) · 938 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module.exports = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('authToken');
if (token)
options.headers.set('Authorization', `Bearer ${token}`);
return fetch(url, options).then(response => {
if (response.ok) {
const contentType = response.headers.get('content-type')
if (response.status === 201) {
return { headers: response.headers, json: {} }
} else if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json().then(json => { return { headers: response.headers, json: json } })
} else {
return response.text().then(text => { return { headers: response.headers, json: { message: text } } })
}
} else {
return response.text().then(text => {
throw new Error(`${response.status}: ${text}`)
})
}
})
}