koa2实现登录注册功能的示例代码

  

本文介绍了koa2实现登录注册功能的示例代码,分享给大家,具体如下:

  

这个主要结合前几天的内容,做个实际案例的效果

  

版本:   

 koa2实现登录注册功能的示例代码

  

项目结构:

  

 koa2实现登录注册功能的示例代码

  

前几天,我们把注册和登录的页面演示实现了,今天我们主要实现这么几个内容

  
      <李>注册新用户李   <李>判断该邮箱是否注册过李   <李>登录判断是否注册过李   <李>登录时的密码的正确李   
  

本文代码地址:https://github.com/xiaqijian/koa2-lessons/tree/master/lesson6

  

明天,我们将利用会话实现登录状态判断

  

今天的这篇是在之前的代码基础上添加的,我们就晒主要的代码

  

<强> 1。编辑user.js

     //db/user.js   const猫鼬=要求(“。/db”)   const模式=mongoose.Schema;      const ceshiSchema=新模式({   电子邮件:字符串,   名称:字符串,   密码:字符串   });      const MyModel=猫鼬。模型(“用户”,ceshiSchema);         类Userdb {   构造函数(){      }//查询   查询(obj={}) {   返回新的承诺((解决,拒绝)=比;{   MyModel。找到(obj,(呃,res)=比;{   如果(err) {   拒绝(err)   }   解决(res)   })   })   }   queryEmail (em) {   返回新的承诺((解决,拒绝)=比;{   MyModel。找到({电子邮件:em},(呃,res)=比;{   如果(err) {   拒绝(err)   }   const len=res.length   如果(len祝辞=1){//存在   解决(res)   其他}{//不存在   解决(空)   }   })   })   }//保存   保存(obj) {   const m=新MyModel (obj)   返回新的承诺((解决,拒绝)=比;{   m。保存((呃,res)=比;{   如果(err) {   拒绝(err)   }   解决(res)   console.log (res)   })   })      }   }   模块。出口=new Userdb ()      

上面主要查询用户,和保存用户

  

<强> 2。编辑登录注册路由

     //路由器/index.js      const路由器=要求(“koa-router”)//const用户=需要(“. ./db/用户”)   const回家=new路由器()      家get('/',异步(ctx)=比;{   title=笆滓场?   等待ctx。呈现(“指数”,{   标题   })   })//子路由2   const页面=new路由器()      页面。get(/404,异步(ctx)=比;{   让标题=" 404 "   等待ctx。呈现(“犯错”,{   标题   })   })         const登录=new路由器()      登录。get('/',异步(ctx)=比;{   让title=暗锹肌?   等待ctx。呈现(“登录”,{   标题   })   }).邮报》('/',异步(ctx)=比;{   常量数据=https://www.yisu.com/zixun/ctx.request.body   让queryres=等待User.queryEmail (data.email)   console.log (queryres)   如果(queryres) {   如果(queryres [0]。密码===data.password) {   ctx。身体={“代码”:1、   “数据”:queryres [0],   “mesg”:“登录成功的   }   其他}{   ctx。身体={   “代码”:0,   “数据”:{},   “mesg”:“密码错误的   }   }      其他}{   ctx。身体={   “代码”:0,   “数据”:{},   “mesg”:“没有该用户,去注册吧”   }   }   })      常量寄存器=new路由器()      登记。get('/',异步(ctx)=比;{   让title=白⒉帷?   等待ctx。呈现(“注册”,{   标题   })   }).邮报》('/',异步(ctx)=比;{   常量数据=https://www.yisu.com/zixun/ctx.request.body   让queryres=等待User.queryEmail (data.email)   如果(queryres) {   ctx。身体={“代码”:0,   “数据”:{},   “mesg”:“该邮箱已经存在的哦   }   其他}{   等待User.save(数据)   ctx。身体={   “代码”:1、   “数据”:{},   “mesg”:“保存成功的   }   }      })//装载所有子路由   让路由器=new路由器()   路由器。使用('/',home.routes (), home.allowedMethods ())   路由器。使用(“/页”,page.routes (), page.allowedMethods ())   路由器。使用(“/登录”,login.routes (), login.allowedMethods ())   路由器。使用(/注册,register.routes (), register.allowedMethods ())         模块。出口路由器=

koa2实现登录注册功能的示例代码