Interceptors are methods that are triggered before the main method
๐ฆ๐๐ฒ๐ฝ๐
1๏ธโฃ Create Axios instance
let me tell you some benefits of creating an Axios instance
a. if you have multiple API calls, to the same endpoint, you specify baseURL and some headers properties which they in common to avoid
writing the same code multiple times
const instance = axios.create({
baseURL: '',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
what else hmmm ๐ค ๐ค , let me know if you have some ideas in the comment section
2๏ธโฃ ๐๐ฑ๐ฑ ๐ถ๐ป๐๐ฒ๐ฟ๐ฐ๐ฒ๐ฝ๐๐ผ๐ฟ๐ ๐๐ผ ๐ฎ ๐ฐ๐๐๐๐ผ๐บ ๐ถ๐ป๐๐๐ฎ๐ป๐ฐ๐ฒ ๐ผ๐ณ ๐๐ ๐ถ๐ผ๐
const instance = axios.create();
instance.interceptors.request.use(function () {/.../});
๐ด ๐ช๐ฒ ๐ต๐ฎ๐๐ฒ ๐ฎ ๐๐๐ฝ๐ฒ๐ ๐ผ๐ณ ๐ถ๐ป๐๐ฒ๐ฟ๐ฐ๐ฒ๐ฝ๐๐ผ๐ฟ๐
1๏ธโฃ Request interceptor- Assume you want to confirm that your login information is accurate before submitting a request.
You can therefore verify at the interceptor level that your credentials are correct rather than making an actual API call.
If you need to add a token to each request performed, you can create an interceptor that does this for you rather than repeating the token addition logic at each Axios call.
2๏ธโฃ Response interceptor- response interceptors accept two function arguments: the first function is when the response that comes back is a 200 status HTTP response, and the second function is when itโs a status code that falls outside of the 200 range
Top comments (0)