Last active
July 26, 2024 11:30
-
-
Save imkarimkarim/b4ad8fe78447692a94bae25c93dd61f5 to your computer and use it in GitHub Desktop.
axiosInstance.ts
This file contains 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
// axiosInstance example with good logging for developers | |
import axios from 'axios'; | |
import { API_PREFIX, API_URL } from '../config'; | |
import { getUserToken } from '../auth'; | |
const userToken = getUserToken(); | |
const headers: any = {}; | |
if (userToken) { | |
headers.Authorization = `Bearer ${userToken}`; | |
} | |
export const axiosInstance = axios.create({ | |
headers, | |
baseURL: API_URL + API_PREFIX, | |
timeout: 20000, | |
}); | |
axiosInstance.interceptors.response.use( | |
(res) => { | |
console.log( | |
`✅ ${res?.status} ${res?.config?.method.toUpperCase()} ${res?.config?.baseURL + res?.config?.url}`, | |
'\n\npayload:', | |
res?.config?.data, | |
'\n\nresponse:', | |
res?.data?.message || '', | |
res?.data, | |
); | |
// console.log(res); | |
return res; | |
}, | |
async (err) => { | |
console.error( | |
`❌ ${err?.response?.status} ${err?.config?.method.toUpperCase()} ${err?.config?.baseURL + err?.config?.url}`, | |
'\n\npayload:', | |
err?.config?.data, | |
'\n\nresponse:', | |
err?.response?.data?.message || '', | |
err?.response?.data, | |
); | |
return Promise.reject(err); | |
}, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result example: