-
-
Save SarathAdhi/80148721ea168c3b74612f94af6b0f2d to your computer and use it in GitHub Desktop.
How to use axios interceptor in JavaScript
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
import Axios from "axios"; | |
const axios = Axios.create({ | |
baseURL: process.env.SERVER_BASE_URL, | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}); | |
axios.interceptors.response.use( | |
(response) => { | |
if(response.data?.message) alert (response.data.message); | |
return response.data; | |
}, | |
(error) => { | |
alert(error?.response?.data?.error || "Could not connect to server"); | |
return Promise.reject(error?.response?.data); | |
} | |
); | |
axios.interceptors.request.use((config) => { | |
const token = localStorage.getItem("token"); | |
if (token) { | |
config.headers.Authorization = token ? `Bearer ${token}` : ""; | |
} | |
return config; | |
}); | |
export default axios; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment