Axios 인터셉터를 사용하는 4가지 방법

12943 단어 nodewebdevjavascript


액시오스가 무엇인가요?

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.

액시오스 인터셉터란?

An Axios interceptor 라이브러리가 요청을 보내거나 받을 때마다 호출하는 함수입니다. "then"또는 "catch"에 의해 처리되기 전에 요청 또는 응답을 가로챌 수 있습니다.

예시:

// 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);
  });


Axios에서 인터셉터를 제거할 수도 있습니다.

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


인터셉터를 사용하여 모든 요청에 ​​인증 토큰 헤더 삽입

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’);

인터셉터를 사용하여 모든 요청과 응답을 기록합니다.

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/‘);

Axios 인터셉터를 사용한 오류 처리

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;

인터셉터를 사용하여 요청에 속도 제한을 추가합니다.

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);
       });
    });
  }
)

좋은 웹페이지 즐겨찾기