token是後端給前端的一個二維碼, 這個二維碼通常是暗碼, 前端拿着這個二維碼到後端, 後端即可以經過這個二維碼得知用戶是否登陸過, 用戶是誰等信息(具體什麼信息,是後端在返回token時候設置的); 前端
nodejs裏的插件: jsonwebtoken;使用方法:vue
app.post('/api/login', (req, res) =>{ const { userName,password} = req.body; login(userName, password,function(data){ if(data[0]){ bcrypt.compare(password, data[0].password).then(function(result) { if(result){ fs.readFile('./TOKEN/TOKEN_EV',(err,data)=>{ const serateKey = data.toString(); res.status(200).json({ userName, token: jwt.sign({ id: data[0].id}, serateKey) }) }) }else{ res.status(422).json({message:'密碼不匹配'}) } }); }else{ res.status(422).json({message:'用戶名不存在'}) } })
axios.interceptors.request.use( config => { if (localStorage.JWT_TOKEN) { // 判斷是否存在token,若是存在的話,則每一個http header都加上token config.headers.Authorization = `token ${localStorage.JWT_TOKEN}`;//這個字符串裏的token能夠不寫 } return config; }, err => { return Promise.reject(err); });
router.beforeEach(({name}, from, next) => { // 獲取 JWT Token if (localStorage.getItem('JWT_TOKEN')) { // 若是用戶在login頁面 if (name === 'login') { next('/'); } else { next(); } } else { if (name === 'login') { next(); } else { next({name: 'login'}); } }
app.get('/api/profile', (req, res) => { //查看請求頭信息 const token = req.headers.authorization.split(' ').pop(); //獲取請求頭的信息 fs.readFile('./TOKEN/TOKEN_EV', (err, result) => {//讀取token的祕鑰, 能夠把這個祕鑰文件存起來, 而後讀取後引入,沒必要每次都讀取 if (!err) { jwt.verify(token, result, (err, decoded) => { const id = decoded.id; //這裏根據id處理 Profile(id, (data) => {//這是業務層的東西, 讀取數據庫, 而後返回數據, 不用管 res.json(data[0]) }) }); } else { res.send(err) } }); })