Created
September 20, 2020 12:05
-
-
Save EgehanGundogdu/71488b472042a1f2e5935156787206d1 to your computer and use it in GitHub Desktop.
axios interceptors usage
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 client = axios.create({ | |
baseURL: process.env.BACKEND_API_URL || "hardcoded backend app url", | |
headers: { | |
"Content-Type": "application/json", | |
}, | |
}); | |
client.interceptors.request.use( | |
(config) => { | |
let token = localStorage.getItem("accessToken") || ""; | |
config.headers["Authorization"] = `Token ${token}`; | |
return config; | |
}, | |
(error) => { | |
return Promise.reject(error); | |
} | |
); | |
client.interceptors.response.use( | |
(response) => { | |
// Any status code that lie within the range of 2xx cause this function to trigger | |
return response; | |
}, | |
(error) => { | |
// Any status codes that falls outside the range of 2xx cause this function to trigger | |
if (error.response.status == 401) { | |
localStorage.removeItem("accessToken"); | |
router.push({ name: "login" }); | |
} | |
return Promise.reject(error); | |
} | |
); | |
export default client; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment