Last active
June 8, 2024 22:59
-
-
Save gabrielfreirebraz/97237798fec79faafdcc4121209633cc to your computer and use it in GitHub Desktop.
Axios configuration to api requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios' | |
export const api = axios.create({ | |
baseURL: 'http://localhost:3000', | |
headers: { | |
'Content-Type': 'application/json', | |
}, | |
timeout: 10000, // Timeout de 10 segundos | |
}) | |
// Adiciona um interceptador para incluir um token de autenticação (se necessário) | |
api.interceptors.request.use( | |
(config) => { | |
const token = localStorage.getItem('token'); // Ou outro método para obter o token | |
if (token) { | |
config.headers.Authorization = `Bearer ${token}`; | |
} | |
return config; | |
}, | |
(error) => { | |
return Promise.reject(error); | |
} | |
); | |
// Adiciona um interceptador para lidar com respostas | |
api.interceptors.response.use( | |
(response) => { | |
return response; | |
}, | |
(error) => { | |
// Lida com erros de forma centralizada | |
if (error.response && error.response.status === 401) { | |
// Por exemplo, redirecionar para a página de login em caso de 401 Unauthorized | |
window.location.href = '/login'; | |
} | |
return Promise.reject(error); | |
} | |
); | |
// example | |
api.get('/users', { | |
params: { | |
id: 1 | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment