Nuxt 3 处理 401 错误并刷新用户令牌

huangapple go评论67阅读模式
英文:

Nuxt 3 handle 401 error and refresh user token

问题

处理401错误、刷新用户令牌并重复请求的最佳方法是使用Nuxt 3的useFetch组合式。

英文:

What is the best way to handle 401 error, refresh user token and repeat request using Nuxt 3 useFetch composable?

答案1

得分: 1

export function useFetchWithAuth(url, options) {
  const instance = axios.create();

  instance.interceptors.response.use(
    (response) => response,
    (error) => {
      if (error.response.status === 401) {
        // 刷新访问令牌。
        
        // 重试原始请求。
        return instance(error.config);
      }

      return Promise.reject(error);
    }
  );

  const fetch = useFetch(instance);

  return async ({ ...opts }) => {
    const { data } = await fetch(url, {
      ...options,
      ...opts,
    });

    return data;
  };
}
<script setup>
const fetch = useFetchWithAuth();

    async function makeRequest() {
      const response = await fetch('/api/users');
    }
</script>

希望这能帮到你。

英文:

You can try this with the help of axios instance interceptors

export function useFetchWithAuth(url, options) {
  const instance = axios.create();

  instance.interceptors.response.use(
    (response) =&gt; response,
    (error) =&gt; {
      if (error.response.status === 401) {
        // Refresh the access token.
        

        // Retry the original request.
        return instance(error.config);
      }

      return Promise.reject(error);
    }
  );

  const fetch = useFetch(instance);

  return async ({ ...opts }) =&gt; {
    const { data } = await fetch(url, {
      ...options,
      ...opts,
    });

    return data;
  };
}

Then you can use in component class:

&lt;script setup&gt;
const fetch = useFetchWithAuth();

    async function makeRequest() {
      const response = await fetch(&#39;/api/users&#39;);

    }
&lt;/script&gt;

Hope this help.

huangapple
  • 本文由 发表于 2023年2月18日 01:21:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487409.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定