提问人:Jesus Salcedo 提问时间:10/24/2023 更新时间:10/24/2023 访问量:58
在 Nuxt 3 中处理 http 请求和响应的更好方法
A better way to handle http request and responses in Nuxt 3
问:
我正在寻找一种方法来拦截所有 http 请求并在 Nuxt3 中应用刷新令牌逻辑,我创建了一个自定义 api 可组合项,有时有效,但我意识到并非所有 useFetch 请求都通过我的自定义api.ts idk 如何改进这一点。
import Cookies from "js-cookie";
import { HTTP_STATUS } from "~/utils/constants/http";
const config = useRuntimeConfig();
let token = Cookies.get("access");
const refresh = Cookies.get("refresh");
// Default useFetch handler
export const useApi = (url, options) => {
return useFetch(url, {
onRequest({ request, options }) {
options.headers = options.headers || {};
if (token) options.headers = { Authorization: `Bearer ${token}` };
},
onResponseError({ request, response, options }) {
console.error(response);
if (response.status == HTTP_STATUS.UNAUTHORIZED) callRefreshToken();
},
...options,
});
};
// Call the refresh token endpoint to renovate the access
const callRefreshToken = () => {
useApi(`${config.public.baseURL}/authentication/token/refresh/`, {
method: "POST",
body: {
refresh,
},
onResponse({ request, response, options }) {
if (response.status == HTTP_STATUS.OK) {
Cookies.set("access", response._data?.access);
token = response._data?.access;
}
window.location.reload();
},
});
};
答: 暂无答案
评论