我有一个基于 vuejs 构建的 SPA。当用户通过 API 登录时, token 存储在本地存储中。
我需要一个全局解决方案,它会在 token 不再有效时注销并提示用户。目前,我在访问私有(private) API 端点时收到“无效 token ”错误。
我如何设置 axios 以便所有无效 token 的响应都将触发注销/提示代码?
最佳答案
这是一个使用 axios
的简单示例。它使用 Bearer token 进行身份验证。
import axios from "axios";
import { useUserStore } from "@/store/userStore";
const apiClient = axios.create({
baseURL: ""http://127.0.0.1:8001",
headers: {},
});
apiClient.interceptors.response.use(
(response) => response,
async (error) => {
const config = error?.config;
if (error?.response?.status === 401) {
const result = await refreshToken();
if (result) {
config.headers = {
...config.headers,
authorization: `Bearer ${result?.token}`,
};
}
return axios(config);
}
);
const refreshToken = async () => {
/* do stuff for refresh token */
// if refresh token failed
try {
useUserStore().actionLogout();
} catch (error) {
console.log(error);
} finally {
loacalStorage.clear();
}
};
关于vue.js - token 失效时自动注销用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45808427/
相关文章:
java - 反编译MCP报错(9.18版)返回 'Decompile Failed' 1
c# - 更改 RedirectUri、Nginx 和 ASP.NEt Core
azure - Azure WebApp 是否自动进行速率限制/DOS 保护?
php - 找不到属性 Application\Sonata\NewsBundle\Entity\P
selenium - 使用 SendKeys 向 IE 11 发送 '@' 特殊字符
apache-spark - Kafka 结构化流 java.lang.NoClassDefFoun