以下内容作为自己学习笔记,仅供参考
axios拦截器代码地址:https://github.com/axios/axios?tab=readme-ov-file#interceptors
login页面提交表单,访问接口‘/adminapi/user/login’
axios.post("/adminapi/user/login",loginForm).then(res=>{ if(res.data.ActionType === "OK"){ store.commit("changeUserInfo",res.data.data) router.push("/index") }else{ ElMessage.error('用户名和密码不匹配') } })
后端收到请求,建立时效性token并回复给前端
login:async (req,res)=>{ var result = await UserService.login(req.body) if(result.length === 0){ res.send({ code:"-1", error:"用户名密码不匹配" }) }else{ const token = JWT.generate({ _id:result[0]._id, username:result[0].username },"1d") res.header("Authorization",token) res.send({ ActionType:"OK", data:{ username:result[0].username, gender:result[0].gender ? result[0].gender : 0, introduction:result[0].introduction, avatar:result[0].avatar, role:result[0].role //管理员:1 编辑:2 } }) } }
在axios拦截器处理token信息。上述后端发送回复,axios响应拦截器获取用户信息并存入到本地localStorage中。当访问其他页面,发送请求时,axios请求拦截器读取‘token’发送请求,后端处理请求。
import axios from "axios"; // Add a request interceptor axios.interceptors.request.use(function (config) { // Do something before request is sent const token = localStorage.getItem("token") config.headers.Authorization = `Bearer ${token}` return config; }, function (error) { // Do something with request error return Promise.reject(error); }); // Add a response interceptor axios.interceptors.response.use(function (response) { // Any status code that lie within the range of 2xx cause this function to trigger // Do something with response data // console.log(response.headers) const {authorization} = response.headers authorization && localStorage.setItem("token",authorization) return response; }, function (error) { // Any status codes that falls outside the range of 2xx cause this function to trigger // Do something with response error const {status} = error.response if(status === 401){ localStorage.removeItem("token") window.location.href = "#/login" } return Promise.reject(error); });
获取‘token’信息并验证,创建新的token信息(newToken)并回复前端。当过了时效期,刷新页面token被移除,跳转到 login 页面
app.use((req,res,next)=>{ if(req.url === '/adminapi/user/login'){ next() return ; } const token = req.headers["authorization"].split(" ")[1] if(token){ var payload = JWT.verify(token) if(payload){ const newToken = JWT.generate({ _id:payload._id, username:payload.username },"1d") res.header("Authorization",newToken) next() }else{ res.status(401).send({errCode:"-1",errorInfo:"token过期"}) } } })