const Koa = require('koa'); // Koa 为一个class
const Router = require('koa-router') // koa 路由中间件
const bodyParser = require('koa-bodyparser'); // 处理post请求,把 koa2 上下文的表单数据解析到 ctx.request.body 中
const jwt = require( 'jsonwebtoken');
const app = new Koa();
const router = new Router(); // 实例化路由
app.use(bodyParser())
// 表单
router.post('/login', async (ctx, next) => {
if (!ctx.request.body.phone) {
ctx.body = { err: '无效参数phone' }
} else if (!ctx.request.body.password) {
ctx.body = { err: '无效参数password' }
} else {
let data = null
//生成token
const token = jwt.sign(
{
name: ctx.request.body //需要放到token的参数
},
'suzhen', //随便一点内容,加密的密文,私钥对应着公钥
{
expiresIn: 60 * 2 //2分钟到期时间
}
)
data = { _id:123 } //项目中走数据库验证
if (data)
ctx.body = {
data: { user_id: data._id, token: token },
message: '登陆成功'
}
else ctx.body = { message: '登陆失败' }
}
})
router.get('/', async (ctx, next) => {
ctx.body = { message: '测试token' }
})
app.use(async (ctx, next) => {
let { url = '' } = ctx
if (!url.includes('/login')) { //除去登陆,注册,找回密码等接口其他的都需要验证
//需要校验登录态
if (!ctx.headers.token) {
return (ctx.body = {
err: '无效token1'
})
} else {
try {
let token = await jwt.verify(
ctx.headers.token,
'suzhen'
)
console.log("====tokenname====",token.name)
if (token.name) await next()
else return (ctx.body = { err: '无效token2' })
} catch (error) {
console.log(error)
return (ctx.body = { err: '无效token3' })
}
}
} else {
await next()
}
})
app.use(router.routes());
app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
网友评论