nuxtjs中的ofetch怎么做无感刷新

erhj 发布于 11/17 12:58
阅读 154
收藏 0

鸿蒙原生应用开发者激励计划发布!最高获百万现金!点击立即参与

 接口返回401就会进入onResponseError函数,在onResponseError里面会刷新token并重新发送请求,但是不管这个函数返回什么结果请求处理函数都会收到reject。 

export default defineNuxtPlugin((nuxtApp) => {
  const settings = useSettings();
  const api: ReturnType<typeof $fetch.create> = $fetch.create({
    onResponseError: async ({ request, options, error, response }) => {
      const route = useRoute();
      let data = response._data;

      if (response.status === 401) {
        const result = await api("/api/auth/refreshToken");
        if (result.success) {
          return api(request, options);
        } else {
          await nuxtApp.runWithContext(() =>
            navigateTo(`/login/?redirectUri=${route.fullPath}`, { replace: true }),
          );
        }
      } else {
        const toast = useToast();
        toast.add({
          color: "red",
          title: `${response.status} ${response.statusText}`,
          description: data.message,
          icon: "i-heroicons-x-mark-20-solid",
        });
      }

      return Promise.reject(response._data);
    },
  });

  return {
    provide: {
      api,
    },
  };
});

 

加载中
0
e
erhj
    async onResponseError({ request, options, error, response }) {
      const route = useRoute();
      let data;
      if (response._data instanceof ReadableStream) {
        const reader = response._data.getReader();
        const decoder = new TextDecoder("utf-8");
        let chunk = "";
        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            data = JSON.parse(chunk);
            break;
          }
          chunk += decoder.decode(value);
        }
        response._data = data;
      } else {
        data = response._data;
      }

      if (response.status === 401) {
        const result = await api("/api/auth/refreshToken");
        if (result.success) {
          options.retryStatusCodes = [401];
          options.retryDelay = 0;
          options.retry = 1;
        } else {
          await nuxtApp.runWithContext(() =>
            navigateTo(`/login/?redirectUri=${route.fullPath}`, { replace: true }),
          );
        }
      } else {
        const toast = useToast();
        toast.add({
          color: "red",
          title: `${response.status} ${response.statusText}`,
          description: data.message,
          icon: "i-heroicons-x-mark-20-solid",
        });
      }
    },

 

0
e
erhj
    async onResponseError({ request, options, error, response }) {
      const route = useRoute();
      let data;
      if (response._data instanceof ReadableStream) {
        const reader = response._data.getReader();
        const decoder = new TextDecoder("utf-8");
        let chunk = "";
        // eslint-disable-next-line no-constant-condition
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            data = JSON.parse(chunk);
            break;
          }
          chunk += decoder.decode(value);
        }
        response._data = data;
      } else {
        data = response._data;
      }

      if (response.status === 401) {
        const result = await api("/api/auth/refreshToken");
        if (result.success) {
          options.retryStatusCodes = [401];
          options.retryDelay = 0;
          options.retry = 1;
        } else {
          await nuxtApp.runWithContext(() =>
            navigateTo(`/login/?redirectUri=${route.fullPath}`, { replace: true }),
          );
        }
      } else {
        const toast = useToast();
        toast.add({
          color: "red",
          title: `${response.status} ${response.statusText}`,
          description: data.message,
          icon: "i-heroicons-x-mark-20-solid",
        });
      }
    },

 

OSCHINA
登录后可查看更多优质内容
返回顶部
顶部