在nodejs后端开发中,需要给前端返回token(令牌),使用 jsonwebtoken
// 下载第三方包
pnpm install jsonwebtoken
使用 jsonwebtoken 生成 token
// 引入
const jwt = require("jsonwebtoken");
// 使用
// 三个参数
// 第一个参数: 希望保存在token的数据
// 第二个参数: 秘钥 解密token的时候还需使用
// 第三个参数: token有效期
// 例:
// 60 : 表示 60 秒
// 2 days : 表示 2 天
// 10h : 表示 10 小时
// 7d : 7d
const token = jwt.sign({user: '1234'}, 'MIYAO', {expiresIn: 60 * 60})
对 token 进行验证
// 引入
const jwt = require("jsonwebtoken");
// 解密
const token = "you-token";
const secretKey = 'your-secret-key';
try {
// 两个参数
// 第一个参数: 前端传递过来的 token
// 第二个参数: 设置的私钥
const decoded = jwt.verify(token, secretKey);
// 令牌验证成功,`decoded`将包含解码后的令牌数据
console.log(decoded);
} catch (error) {
// 令牌验证失败
console.error('Token verification failed:', error.message);
}