该项目是一整个专栏,主要是使用node+express+ts+mysql,来完成一个小程序+后台管理的node后端项目,喜欢的可以订阅此专栏。
1.引入jsonwebtoken包
npm i jsonwebtoken
2.在文件中引入jsonwebtoken
//app.ts
//引入express
import express from "express";
//引入jwt
import jwt from "jsonwebtoken";
const app = express();
3.做一个接口路径为'/login'的接口
const secretKey = "secret";//此处随便写就可以
app.post("/login", (req, res) => {
// 登录失败
if (req.body.username !== "admin" && req.body.password !== "123321") {
return res.send({
status: "400",
message: "登录失败",
});
}
var tokenStr = jwt.sign({ username: req.body.username }, secretKey, {
expiresIn: 60 * 60 * 1,//表示1小时失效
});
res.send({
status: 200,
message: "登录成功",
token: tokenStr,
});
});
4.做一个中间间来效验token
//中间件
const authToken = (req: any, res: any, next: any) => {
const token = req.headers["session-token"];//此处为效验请求头中所存在的token
console.log(token);
if (!token) {
return res.send({
success: false,
msg: "token错误",
});
}
const decoded = jwt.verify(token, secretKey);
next();//next()必须存在,否则会出现请求死循环
};
5.来写一个接口进行测试
//定义接口测试
app.get("/user/info", authToken, (req: any, res) => {
return res.send({
status: 200,
message: "请求成功!",
});
});
6.写一个错误中间件来维护报错
app.use((err: any, req: any, res: any, next: () => void) => {
// 如果错误是由token解析失败导致的
if (err.name === "UnauthorizedError") {
return res.send({
status: 401,
message: "无效的token",
});
}
res.send({
status: 500,
message: "未知的错误",
});
next();
});
7.完结
目前来看,已经实现jsonwebtoken的使用,现在放出完整代码查缺补漏
//app.ts
import express from "express";
import jwt from "jsonwebtoken";
const app = express();
const secretKey = "secret";
app.post("/login", (req, res) => {
// 登录失败
if (req.body.username !== "admin" && req.body.password !== "123321") {
return res.send({
status: "400",
message: "登录失败",
});
}
var tokenStr = jwt.sign({ username: req.body.username }, secretKey, {
expiresIn: 60 * 60 * 1,
});
res.send({
status: 200,
message: "登录成功",
token: tokenStr,
});
});
const authToken = (req: any, res: any, next: any) => {
const token = req.headers["session-token"];
console.log(token);
if (!token) {
return res.send({
success: false,
msg: "token错误",
});
}
var decoded = jwt.verify(token, secretKey);
console.log(decoded);
next();
};
app.get("/user/info", authToken, (req: any, res) => {
return res.send({
status: 200,
message: "请求成功!",
data: {
age: 18,
gender: "男",
username: 'admin',
},
});
});
app.use((err: any, req: any, res: any, next: () => void) => {
// 如果错误是由token解析失败导致的
if (err.name === "UnauthorizedError") {
return res.send({
status: 401,
message: "无效的token",
});
}
res.send({
status: 500,
message: "未知的错误",
});
next();
});
app.listen(80, "127.0.0.1", () => {
console.log("server is running on port http://127.0.0.1");
});