1-1 登陆页的html页面

  1. //login.html
  2. <form action="/doLogin" method="post">
  3. <!-- name属性:可以将前台的数据提交到后台 -->
  4. 用户名: <input type="text" name="username" placeholder="请输入用户名">
  5. 密码: <input type="password" name="pwd" placeholder="请输入密码">
  6. <input type="submit">
  7. </form>

1-2 登陆页对应的路由

  1. router.get("/login",async ctx=>{
  2. await ctx.render("login.html")
  3. })

1-3 提交数据的路由页面

  1. router.post("/doLogin",async ctx=>{
  2. console.log(ctx.request.body) // post传值
  3. var {username,pwd} = ctx.request.body;
  4. /* data是从数据库中取得的数据 */
  5. var data = {username:"cheng",pwd:123456}
  6. if(data.username == username && data.pwd == pwd){
  7. await ctx.redirect("/") // 路由重定向
  8. }else{
  9. ctx.body = (`<script>alert("登陆失败用户名或密码错误");location.href="/login"</script>`)
  10. }
  11. })

1-4 登陆拦截中间件

  1. app.use(async (ctx,next)=>{
  2. // ctx.path可以获取路由地址
  3. /* 1.登陆页 */
  4. if(ctx.path == "/login" || ctx.path == "/doLogin"){
  5. await next();
  6. }else{
  7. /* 不在登陆页 */
  8. if(ctx.cookies.get("name")){
  9. /* 已经登陆了 */
  10. await next();
  11. }else{
  12. /* 没有登陆 */
  13. await ctx.redirect("/login")
  14. }
  15. }
  16. })