英文:
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) => response,
(error) => {
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 }) => {
const { data } = await fetch(url, {
...options,
...opts,
});
return data;
};
}
Then you can use in component class:
<script setup>
const fetch = useFetchWithAuth();
async function makeRequest() {
const response = await fetch('/api/users');
}
</script>
Hope this help.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论