const express = require('express') const jwt = require('jsonwebtoken') const expressJWT = require('express-jwt')
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended:false}))
const secretKey = 'miyao'
app.use(expressJWT( { secret: secretKey , algorithms: ["HS256"], } ).unless({ path: [/^\/api\//] }))
app.post('/api/login' , (req , res)=>{ console.log(req.body); if (req.body.username !== 'lam' || req.body.password !== '123') { return res.send({ status: 400, msg: '登录失败' }) }
const tokenStr = jwt.sign( {username:req.body.username}, secretKey, { expiresIn: '30h' } ) res.send({ status: 200, message: '登录成功!', token: tokenStr, }) })
app.get('/admin/getinfo', function (req, res) { console.log(req.user) res.send({ status: 200, message: '获取用户信息成功!', data: req.user, }) })
app.use((err, req, res, next) => { if (err.name === 'UnauthorizedError') { return res.send({ status: 401, message: '无效的token', }) } res.send({ status: 500, message: '未知的错误', }) })
app.listen(3000,()=>{ console.log('服务器已启动,3000端口正在监听...'); })
|