Last active
April 1, 2020 07:18
-
-
Save kianaditya/ec44e4d4e4847d0054a5b49e3ee1c9bf to your computer and use it in GitHub Desktop.
Axios requests interceptor example
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 Credentials from "./Credentials"; | |
const axios = require("axios"); | |
const http = axios.create(); // Creates new axios instance | |
const credentials = new Credentials(); // Gets access to all credentials functions | |
http.interceptors.request.use( | |
async config => { | |
const token = await credentials.getCredentials(); // Gets credentials from localStorage | |
if (token) config.headers.Authorization = `Bearer ${token}`; // Inserts credentials as bearer token in request headers | |
return config; | |
}, | |
error => { | |
return Promise.reject(error); | |
} | |
); | |
// Exposes all API end points as appropriate functions | |
export default { | |
api: { | |
getChapters() { | |
return http.get(`${process.env.REACT_APP_API_BASE_URL}/api/v1/chapters`); | |
}, | |
getSpecificChapter(chapter) { | |
return http.get(`${process.env.REACT_APP_API_BASE_URL}/api/v1/chapters/${chapter}`); | |
}, | |
getVerses() { | |
return http.get(`${process.env.REACT_APP_API_BASE_URL}/api/v1/verses`); | |
}, | |
getVersesFromChapter(chapter) { | |
return http.get( | |
`${process.env.REACT_APP_API_BASE_URL}/api/v1/chapters/${chapter}/verses` | |
); | |
}, | |
getSpecificVerse(chapter, verse) { | |
return http.get( | |
`${process.env.REACT_APP_API_BASE_URL}/api/v1/chapters/${chapter}/verses/${verse}` | |
); | |
}, | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment