接口返回 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,
},
};
});
转载请注明:可思数据 » nuxtjs 中的 ofetch 怎么做无感刷新