1-1 安装依赖

  1. yarn init -y
  2. yarn add koa koa-router koa-body koa-static koa-mongodb
  3. yarn add koa-art-template art-template

image.png

1-2 封装

(1)

  1. //config-index.js
  2. const router=require("../routers");
  3. const koaBody=require("koa-body");
  4. const static=require("koa-static");
  5. const render=require("koa-art-template")
  6. const path=require("path");
  7. // const fs=require("fs")
  8. function initProject(app){
  9. app.use(koaBody());
  10. app.use(router.routes());
  11. var res=path.join(process.cwd(),'static')
  12. // console.log(res);
  13. app.use(static(path.join(process.cwd(),"static")));
  14. render(app, {
  15. root: path.join(process.cwd(), 'pages'),
  16. extname: '.html',
  17. debug: process.env.NODE_ENV !== 'production'
  18. });
  19. }
  20. module.exports=initProject;

image.png

(2)

  1. const router=require("koa-router")();
  2. const main=require("../models")
  3. router.get("/login", async ctx=>{
  4. await ctx.render("login")
  5. })
  6. router.get("/register", async ctx=>{
  7. await ctx.render("register")
  8. })
  9. router.get("/home", async ctx=>{
  10. ctx.body="home"
  11. })

image.png

1-3 注册

  1. router.post("/doRegister",async ctx=>{
  2. console.log(ctx.request.body);
  3. var {username,pwd}=ctx.request.body;
  4. var userCollection=await main("user");
  5. /* 对user查询,没有username才添加 */
  6. var res=await userCollection.find({username}).toArray();
  7. /* 1.用户名存在,停留在注册页面 */
  8. if(res.length){
  9. ctx.body="<script>alert('用户名已存在');location.href='/register'</script>"
  10. }else{
  11. /* 2. 用户名不存在,注册-进入首页 */
  12. var res=await userCollection.insertOne({username,pwd});
  13. ctx.body="<script>alert('注册成功');location.href='/home'</script>"
  14. }
  15. console.log(res);
  16. })

1-4 登录

  1. router.post("/doLogin",async ctx=>{
  2. var {username,pwd}=ctx.request.body;
  3. var userCollection=await main("user")
  4. var res=await userCollection.find({username,pwd}).toArray()
  5. if(res.length){
  6. await ctx.redirect("/home")
  7. }else{
  8. ctx.body="<script>alert('用户名或密码错误');location.href='/login'</script>"
  9. }
  10. })