reactjs 如何在Next JS中使用拦截器

rks48beu  于 2023-01-08  发布在  React
关注(0)|答案(1)|浏览(376)

我在NextJS中使用axios时遇到了麻烦,原因很简单,拦截器在一个请求或响应中被多次调用。
我只是把拦截器放在_app. tsx组件中,它们正在工作,唯一的问题是它们被调用了不止一次。
如果你能帮助我,我将不胜感激!
下面是我的代码:

// ** Axios Configs
  axios.defaults.baseURL = 'http://localhost:3333';

  // ** Request Interceptor
  axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      console.log('ok request');

      // ** Get token from localStorage
      const accessToken = window.localStorage.getItem(authConfig.storageTokenKeyName)

      // ** If token is present add it to request's Authorization Header
      if (accessToken) {
        // ** eslint-disable-next-line no-param-reassign
        if (config.headers)
          config.headers.Authorization = accessToken;
      }
      return config;
    },
    (error) => {
      console.log('ok, errors 1')
      return Promise.reject(error)
    }
  );

  // ** Add request/response interceptor
  axios.interceptors.response.use(
    (response) => {
      console.log('response >', response)
      return response
    },
    (error) => {
      const { config, response } = error;

      if (response && response?.status === 401) {
        router.push('/401');
      } else if (
        response?.data &&
        (
          response?.status === 500 ||
          response?.status === 400
        )
      ) {
        if (typeof response.data?.error === 'string') {
          toast.error(response.data?.error, { duration: 3000 })
        } else {
          toast.error('Houve um erro desconhecido. Tente novamente ou contate o suporte!', { duration: 3000 })
        }
      } else if (response?.data && response?.status === 409) {
        if (response.data.message) {
          response.data.message.map((item: { message: string }) => {
            toast.error(item.message, { duration: 3000 })
          })
        } else {
          toast.error(response.data.error, { duration: 3000 })
        }
      } else if (error?.code === "ERR_NETWORK") {
        toast.error('Ops! Houve de conexão. Tente novamente.', { duration: 3000 })
      } else {
        toast.error('Ops! Houve um erro desconhecido ao executar esta ação', { duration: 3000 })
      }
      console.log('ok, errors 2')
      return Promise.reject(error);
    }
  );

我尝试过将拦截器移到index.tsx,但遇到了同样的问题

92dk7w1h

92dk7w1h1#

对我来说,问题是拦截器通过应用程序累积。
因此,在修复这个问题时,对我有效的解决方案是在每次组件要卸载时弹出拦截器

var myInterceptor = axios.interceptors.response.use(...)    
interceptors.request.eject(myInterceptor)

相关问题