package.json
"scripts": {
"start": "nodemon src/main.ts",
"start:a": "nodemon src/a.ts",
"build": "tsc",
"build:dev": "tsc src/main.ts"
},
express服务器文件
import * as express from 'express';
import { Request, Response, NextFunction } from 'express'
import * as jwt from 'jsonwebtoken';
const app = express();
const secretKey = 'sean';
app.use(express.static("static"))
interface AuthenticatedRequest extends Request {
user?: any;
}
// 登录接口
app.post('/login', (req: AuthenticatedRequest , res: Response) => {
// 假设登录验证成功,生成Token
const token = jwt.sign({ username: 'admin' }, secretKey, { expiresIn: '1h' });
res.json({ token });
});
// 验证Token的中间件
const authenticateToken = (req: AuthenticatedRequest , res: Response, next: NextFunction) => {
const authHeader = req.headers['authorization'];
console.log("authHeader:",authHeader)
// const token = authHeader && authHeader.split(' ')[1];
const token = authHeader;
console.log("token:",token)
if (token == null) {
return res.sendStatus(401);
}
jwt.verify(token, secretKey, (err: any, user: any) => {
if (err) {
console.log("verify-err",err)
return res.sendStatus(403);
}
req.user = user;
next();
});
};
// 需要验证Token的接口
app.get('/protected', authenticateToken, (req: AuthenticatedRequest, res: Response) => {
console.log("req",req)
res.json({ message: 'Protected route', user: req.user });
});
app.get('/list', authenticateToken, (req: AuthenticatedRequest, res: Response) => {
console.log("req",req)
res.json({ data: [] });
});
app.get("/static",(req,res)=>{
res.sendFile("index.html",{root:"./"})
})
// 启动服务器
app.listen(4000, () => {
console.log('Server is running on port 4000');
});
在根目录新建一个index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<form >
<div>
<span>用户名:</span>
<input id="user" type="text" placeholder="please input username">
</div>
<div>
<span>密码:</span>
<input id="password" type="password" placeholder="please input username">
</div>
<div>
<button id="btn">提交</button>
</div>
</form>
<div >
<button id="send">send</button>
</div>
<div >
<button id="listBtn">获取list</button>
</div>
</div>
</body>
</html>
<script>
let user=document.getElementById("user")
let password=document.getElementById("password")
let btn=document.getElementById("btn")
let sendBtn=document.getElementById("send")
let listBtn=document.getElementById("listBtn")
const submit=(e)=>{
e.preventDefault()
let data={
username:user.value,
password:password.value
}
fetch("http://localhost:4000/login",{method:"post",body:JSON.stringify(data)}).then(res=>{
res.json().then(res=>{
console.log("response",res)
let token=res.token;
sessionStorage.setItem("authorization",token)
})
})
console.log("data",data)
}
const request=()=>{
fetch("http://localhost:4000/protected",{
method:"get",
headers:{
"authorization":sessionStorage.getItem("authorization")
}
}).then(res=>{
res.json().then(response=>{
console.log("pretect--response",response)
})
})
}
const requestList=()=>{
fetch("http://localhost:4000/list",{
method:"get",
headers:{
"authorization":sessionStorage.getItem("authorization")
}
}).then(res=>{
res.json().then(response=>{
console.log("pretect--response",response)
})
})
}
btn.addEventListener("click",submit)
sendBtn.addEventListener("click",request)
listBtn.addEventListener("click",requestList)
</script>