基于typescript+express实现一个简单的接口权限验证

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>
相关推荐
奔跑草-1 小时前
【前端】深入浅出 - TypeScript 的详细讲解
前端·javascript·react.js·typescript
羡与1 小时前
echarts-gl 3D柱状图配置
前端·javascript·echarts
前端郭德纲1 小时前
浏览器是加载ES6模块的?
javascript·算法
JerryXZR1 小时前
JavaScript核心编程 - 原型链 作用域 与 执行上下文
开发语言·javascript·原型模式
帅帅哥的兜兜1 小时前
CSS:导航栏三角箭头
javascript·css3
渗透测试老鸟-九青2 小时前
通过投毒Bingbot索引挖掘必应中的存储型XSS
服务器·前端·javascript·安全·web安全·缓存·xss
龙猫蓝图2 小时前
vue el-date-picker 日期选择器禁用失效问题
前端·javascript·vue.js
夜色呦2 小时前
掌握ECMAScript模块化:构建高效JavaScript应用
前端·javascript·ecmascript
peachSoda72 小时前
随手记:简单实现纯前端文件导出(XLSX)
前端·javascript·vue.js
大叔是90后大叔2 小时前
vue3中查找字典列表中某个元素的值对应的列表索引值
开发语言·前端·javascript