You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

29 lines
964 B

const serverUrl = import.meta.env.VITE_SERVER_SUIVI_URL || 'http://localhost:3201'
export const httpRequest = async function(url, { method = 'GET', body }, authentified = false, jsonRequest = false) {
const headers = new Headers()
if (body) {
headers.append('accept', 'application/json')
headers.append('content-type', 'application/json')
}
if (authentified) {
const token = localStorage.getItem('token')
headers.append('authorization', `Bearer ${token}`)
}
const init = { method, headers }
if (body) init.body = JSON.stringify(body);
let _url = url;
if (!_url.startsWith(serverUrl)) _url = `${serverUrl}${url}`;
const res = await fetch(_url, init);
if (res.status === 401) {
localStorage.removeItem('token');
// router.push({ name: 'login' });
} else {
if (jsonRequest) {
const json = await res.json();
if (res.ok) return json;
else return Promise.reject(json);
} else return res;
}
}