// /login登陸接口 router.post('/login', function(req, res, next) { const {userName, password} = req.body if (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 = req.method.tolowerCase() let path = req.path if (whiteListUrl[method] && hasOneOf(path, whiteListUrl[methods])).next() else { const token = req.headers.authorization if (!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.name next() } }) } } })
(1)路由守衛判斷有沒有token,沒有的話進入login頁
(2)若是有的話,從新請求服務器獲取token,放入cookies,進入頁面
(3)login登陸成功後,返回token放入cookies
(4)每次請求的時候headers里加入token驗證後端
後端代碼:服務器
token: jwt.sign({ name: userName }, 'abcd', { expiresIn: 60 })
token設置爲60秒過時,每次請求cookie
跳轉頁面,清除tokenapp