登录
后端部分(token处理在横线区域)
const jwt = require('jsonwebtoken')
const { getUserInfo } = require('../service/user.service')
//登录
async login(ctx) {
//获取数据
const {
user_name
} = ctx.request.body
//操作数据库
console.log(`----获取登录信息:${user_name}----`);
try {
const res = await getUserInfo({
user_name
})
if (res) {
-------------------------------------------
let token = jwt.sign({ res }, 'blog', {
expiresIn: '1d'
})
ctx.cookies.set('blog', token, {
domain: 'localhost',
maxAge: 24 * 60 * 60 * 1000,
overwrite: true,
httpOnly: false
})
-------------------------------------------
ctx.body = {
code: 1,
message: '用户登录成功',
result: {
user_name
},
}
} else {
ctx.body = {
code: 0,
message: '登陆失败'
}
return
}
} catch (err) {
console.error('登录接口错误:', err)
}
}
前端部分
在VueX中处理token(横线区域)
const state = () => {
return {
userInfo: null
};
};
const mutations = {
// 保存登录信息
SET_LOGIN(state, data = null) {
state.userInfo = data;
}
};
const actions = {
// 保存登录信息
saveLogin({ commit }, data = null) {
// 创建有效期为一天的Cookie 保存用户的登录信息
//--------------------------
Cookie.set('USERINFO', JSON.stringify(data), { expires: 1 });
//--------------------------
commit('SET_LOGIN', data);
}
};
修改用户信息
- 修改用户信息也意味着
token应该更新,需要重新生成token并将其保存在cookie中 - 全局
let token,这样在调用saveCookie方法的时候就会获取到最新的token将token更新封装在中间件中
auth.middleware.js
const jwt = require('jsonwebtoken')
let token = ''; //全局let token,这样在调用saveCookie方法的时候就会获取到最新的token
//保存token
const saveToken = (res) => {
token = jwt.sign({ res }, 'blog', {
expiresIn: '1d'
})
}
//设置Cookie
const saveCookie = (ctx) => {
console.log('----设置Cookie----');
ctx.cookies.set('blog', token, {
domain: 'localhost',
maxAge: 24 * 60 * 60 * 1000,
overwrite: true,
httpOnly: false
})
if (ctx.cookies.get('blog')) {
console.log('----设置Cookie成功----');
} else {
console.log('----设置Cookie失败----');
return
}
}
数据层
只要用到此方法的地方都会重新更新token
async updateById({id,user_name......}) {
try {
...
if (resInfo) {
//如果成功修改数据库调用生成token方法
saveToken(resInfo.dataValues)
} else {
return
}
} catch () {
console.error('更改用户信息数据库方法错误:', error);
}
}
此时新的token已经生成,需要在router中调用设置Cookie方法即可前端同步新的token
user.route.js
//修改个人信息
router.post('/edit/info', ...., saveCookie)