Skip to content

Instantly share code, notes, and snippets.

@SarathAdhi
Last active September 12, 2024 16:58
Show Gist options
  • Save SarathAdhi/80148721ea168c3b74612f94af6b0f2d to your computer and use it in GitHub Desktop.
Save SarathAdhi/80148721ea168c3b74612f94af6b0f2d to your computer and use it in GitHub Desktop.
How to use axios interceptor in JavaScript
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