使用 JWT 的 API 请求在 Flask 和 Vue.js 中实现。JWT 存储在 cookie 中,服务器为每个请求验证 JWT。
如果令牌已过期,将返回 401 错误。如果您收到 401 错误,请按照以下代码刷新令牌,再次发出原始 API 请求。以下代码适用于所有请求。
http.interceptors.response.use((response) => {
return response;
}, error => {
if (error.config && error.response && error.response.status === 401 && !error.config._retry) {
error.config._retry = true;
http
.post(
"/token/refresh",
{},
{
withCredentials: true,
headers: {
"X-CSRF-TOKEN": Vue.$cookies.get("csrf_refresh_token")
}
}
)
.then(res => {
if (res.status == 200) {
const config = error.config;
config.headers["X-CSRF-TOKEN"] = Vue.$cookies.get("csrf_access_token");
return Axios.request(error.config);
}
})
.catch(error => {
}); …Run Code Online (Sandbox Code Playgroud)