1-1 登陆页的html页面
//login.html<form action="/doLogin" method="post"> <!-- name属性:可以将前台的数据提交到后台 --> 用户名: <input type="text" name="username" placeholder="请输入用户名"> 密码: <input type="password" name="pwd" placeholder="请输入密码"> <input type="submit"></form>
1-2 登陆页对应的路由
router.get("/login",async ctx=>{ await ctx.render("login.html")})
1-3 提交数据的路由页面
router.post("/doLogin",async ctx=>{ console.log(ctx.request.body) // post传值 var {username,pwd} = ctx.request.body; /* data是从数据库中取得的数据 */ var data = {username:"cheng",pwd:123456} if(data.username == username && data.pwd == pwd){ await ctx.redirect("/") // 路由重定向 }else{ ctx.body = (`<script>alert("登陆失败用户名或密码错误");location.href="/login"</script>`) }})
1-4 登陆拦截中间件
app.use(async (ctx,next)=>{ // ctx.path可以获取路由地址 /* 1.登陆页 */ if(ctx.path == "/login" || ctx.path == "/doLogin"){ await next(); }else{ /* 不在登陆页 */ if(ctx.cookies.get("name")){ /* 已经登陆了 */ await next(); }else{ /* 没有登陆 */ await ctx.redirect("/login") } }})