fetch et axios
Appels API : fetch et axios
fetch natif
async function getUsers() {
const res = await fetch('/api/users', {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
async function createUser(data) {
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
axios
npm install axios
import axios from 'axios';
// Instance configurée
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
});
// Intercepteur pour le token
api.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) config.headers.Authorization = `Bearer ${token}`;
return config;
});
// Intercepteur pour les erreurs
api.interceptors.response.use(
response => response.data,
error => {
if (error.response?.status === 401) logout();
return Promise.reject(error);
}
);
// Utilisation
const users = await api.get('/users');
const user = await api.post('/users', { nom: "Hugo" });
await api.put('/users/1', { nom: "Hugo P." });
await api.delete('/users/1');