Recently in the background login with node to detect the login function. The local use of the session can be successful, but after the server to find the session is invalid, each request session will change, for a long reason. Originally, the project is a front-end separation, the front end of the call back-end API interface, so used cors = require(‘cors‘)
to solve the cross-domain problem, and cross-domain for the cookie, is two different sites, so the session will continue to change.
Cause
Recently in the background login with node to detect the login function. The local use of the session can be successful, but after the server to find the session is invalid, each request session will change, for a long reason. Originally, the project is a front-end separation, the front end of the call back-end API interface, so used cors = require(‘cors‘)
to solve the cross-domain problem, and cross-domain for the cookie, is two different sites, so the session will continue to change.
Workaround
//api.js//登录router.post(‘/api/admin/signIn‘,(req, res)=>{ db.User.find({ name: req.body.name,password: req.body.password},(err, docs)=>{ if (err) { res.send(err); return } if(docs.length>0){ let content ={name:req.body.name}; // 要生成token的主题信息 let secretOrPrivateKey="suiyi" // 这是加密的key(密钥) let token = jwt.sign(content, secretOrPrivateKey, { expiresIn: 60*60*1 // 1小时过期 }); docs[0].token = token //token写入数据库 db.User(docs[0]).save(function (err) { if (err) { res.status(500).send() return } res.send({‘status‘:1,‘msg‘:‘登陆成功‘,‘token‘:token,‘user_name‘:req.body.name}) //反给前台 }) }else{ res.send({‘status‘:0,‘msg‘:‘登录失败‘}); } })})
- The front desk will be able to get tokens and deposit localstorage.
//signin.vue this.$axios.post(webUrl+‘api/admin/signIn‘, {‘name‘: this.name, ‘password‘: this.password}) .then((response) => { if(response.data.status==1){ localStorage.setItem(‘token‘, response.data.token); localStorage.setItem(‘user_name‘, response.data.user_name); }else{ alert(response.data.msg) } }) .catch((reject) => { console.log(reject) })
//Detect Token//api.jsrouter.post ('/api/admin/checkuser ', (req, res) =>{db. User.find ({Name:req.body.user_name,token:req.body.token}, (Err, Docs) =>{if (err) {res.send (err); return} if (docs.length>0) {Let token = Req.body.token;//Get token from body Let secretorprivatekey= "Suiyi"; This is the encrypted key (key) Jwt.verify (token, secretorprivatekey, function (err, decode) {if (err) {// Time Lapse/Forged token res.send ({' status ': 0}); } else {res.send ({' Status ': 1}); }})}else{Res.send ({' status ': 0}); } })})
Node uses Jsonwebtoken to generate tokens, complete user login, login detection