Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8643

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T03:03:08+00:00 2024-11-28T03:03:08+00:00

4 ways to use Axios interceptors

  • 60k

rg45 wires - credit ElasticComputeFarm

What is Axios?

Axios is a promise-based HTTP client for the browser and node.js. It comes with many useful defaults like automatically detecting JSON responses and returning an object instead of plain text, throwing an error if the response status code is greater than 400.

What is an axios interceptor?

An Axios interceptor is a function that the library calls every time it sends or receives the request. You can intercept requests or responses before they are handled by “then” or “catch”.

Example:

// Add a request interceptor axios.interceptors.request.use(function (config) {     // Do something before request is sent     return config;   }, function (error) {     // Do something with request error     return Promise.reject(error);   });  // Add a response interceptor axios.interceptors.response.use(function (response) {     // Any status code that lie within the range of 2xx cause this function to trigger     // Do something with response data     return response;   }, function (error) {     // Any status codes that falls outside the range of 2xx cause this function to trigger     // Do something with response error     return Promise.reject(error);   }); 
Enter fullscreen mode Exit fullscreen mode

You can also remove the interceptor from Axios.

const myInterceptor = axios.interceptors.request.use(function ({/*...*/}); axios.interceptors.request.eject(myInterceptor); 
Enter fullscreen mode Exit fullscreen mode

Inject auth token header in every request using interceptors

There is a big chance when building an app that you will use an API that requires some credentials like api_token or a user Auth token. Usually, you will have to append the required headers with every HTTP request you make. Using Axios interceptors, you can set this up once, and anywhere you call your Axios instance, you are sure that the token is there.

axios.interceptors.request.use(req => {   // `req` is the Axios request config, so you can modify   // the `headers`.   req.headers.authorization = ‘Bearer mytoken’;   return req; });  // Automatically sets the authorization header because // of the request interceptor const res = await axios.get(‘https://api.example.com’); 
Enter fullscreen mode Exit fullscreen mode

Log every request and response using interceptors.

Logging requests can be beneficial, especially when you have a large app and you don’t know where all your requests are triggered. Using an Axios interceptor, you can log every request and response quickly.

const axios = require(‘axios’);  axios.interceptors.request.use(req => {   console.log(`${JSON.stringify(req, null, 2)}`);   // you must return the request object after you are done   return req; });  axios.interceptors.response.use(res => {   console.log(res.data.json);   // you must return the response object after you are done   return res; });  await axios.post(‘https://example.com/‘); 
Enter fullscreen mode Exit fullscreen mode

Error handling using Axios interceptors

You can use An Axios interceptor to capture all errors and enhance them before reaching your end user. If you use multiple APIs with different error object shapes, you can use an interceptor to transform them into a standard structure.

const axios = require(‘axios’); axios.interceptors.response.use(   res => res,   err => {     throw new Error(err.response.data.message);   } ) const err = await axios.get(‘http://example.com/notfound’).   catch(err => err); // “Could not find page /notfound” err.message; 
Enter fullscreen mode Exit fullscreen mode

Add rate limiting to requests using interceptors.

Backend resources are limited and can cost a lot of money. As a client, you help reduce the load on your server by rate-limiting your HTTP calls. Here’s how you can do it using an Axios interceptor.

const axios = require(‘axios’); const debounce = require('lodash.debounce'); axios.interceptors.request.use(   res => { return new Promise((resolve) => { // only fire a request every 2 sec        debounce(           () => resolve(config),2000);        });     });   } ) 
Enter fullscreen mode Exit fullscreen mode

javascriptnodewebdev
  • 0 0 Answers
  • 8 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.