// /login登录接口
router.post('/login', function(req, res, next) {const {userName, password} = req.bodyif (userName) {const userInfo = password ? getPasswordByName(userName) : ''if (!userInfo || !pawwsord || userInfo.password !== password) {res.status(401).send({code: 401,mes: 'user name or password is wrong',data: {}})} else {res.send({code: 200,mes: 'success',data: {token: jwt.sign({ name: userName }, 'abcd', {expiresIn: 60})}})}} else {res.status(401).send({code: 401,mes: 'user name is empty',data: {}})}
})// 接口拦截
const whiteListUrl = {get: {},post: {'/index/login'}
}const hasOneOf = {str, arr} => {return arr.some(item => item.includes(str))
}app.all('*', (req, res, next) => {let method = lowerCase()let path = req.pathif (whiteListUrl[method] && hasOneOf(path, whiteListUrl[methods])).next()else {const token = req.headers.authorizationif (!token) res.status(401).send('there is no token, please login')else {jwt.verify(token, 'abcd', (error, decode) => {if (error) res.send({code: 401,mes: 'token error',data: {}}) else {req.userName = decode.namenext()}})}}
})
(1)路由守卫判断有没有token,没有的话进入login页
(2)如果有的话,重新请求服务器获取token,放入cookies,进入页面
(3)login登录成功后,返回token放入cookies
(4)每次请求的时候headers里加入token验证
后端代码:
token: jwt.sign({ name: userName }, 'abcd', {expiresIn: 60})
token设置为60秒过期,每次请求
跳转页面,清除token
本文发布于:2024-01-28 03:37:07,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17063842334505.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |