V๐—ฎ๐—น๐—ถ๐—ฑ๐—ฎ๐˜ing ๐˜‚๐˜€๐—ฒ๐—ฟ ๐—ฏ๐—ฒ๐—ณ๐—ผ๐—ฟ๐—ฒ ๐—ฎ๐—ป๐˜† ๐—”๐—ฃ๐—œ ๐—ฐ๐—ฎ๐—น๐—น ๐˜‚๐˜€๐—ถ๐—ป๐—ด ๐—”๐˜…๐—ถ๐—ผ๐˜€ ๐—ถ๐—ป๐˜๐—ฒ๐—ฟ๐—ฐ๐—ฒ๐—ฝ๐˜๐—ผ๐—ฟ๐˜€

talent - May 10 '23 - - Dev Community

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

Image description

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player