koa+mongodb实现注册登录

首先要下载对应的包koa,koa-static,koa-view,koa-router,koa-body,@koa/cors,pug和mongoose

然后导入

const Koa=require('koa');
const koa=new Koa();
const {join}=require('path');
const views=require('koa-views');
const router=require('./router');
const static=require('koa-static');
const body=require('koa-body');
koa.use(views(join(__dirname,'view'),{extension:'pug'}));
koa.use(body());
const cors=require('@koa/cors');
koa.use(cors());
koa.use(router.routes());
koa.use(router.allowedMethods());
koa.use(static(join(__dirname,'public')));
koa.listen(5000);

这是app.js文件,监听5000端口号,其中public文件夹下面放pug文件,view文件夹下面放css文件和js文件

doctype html
html(lang="en")
    head
        title= blog
        link(rel='stylesheet' href='/css/one.css')
    body
        div(class='first')
            a(href='/log') 注册
            a(href='/reg') 登录

这是首页xt.pug

doctype html
html(lang="en")
    head
        title= blog
        link(rel='stylesheet' href='/css/index.css')
    body
        div(class='first')
            form(action='/submit' method="POST")
                li
                    span 用户名:
                    input(type='text' name='username')
                li
                    span 密码:
                    input(type='password' name='password')
                li
                    button(type="submit") 登录
        script.
                if('#{success}'){alert('#{success}')}
                if('#{err}'){alert('#{err}')}
                if('#{error}'){alert('#{error}')}
                if ('#{mistake}') {
                        alert('#{mistake}')
                    }

这是登录first.pug

doctype html
html(lang="en")
    head
        title= blog
        link(rel='stylesheet' href='/css/index.css')
    body
        div(class='first')
            form(action='/log' method="POST" )
                li
                    span 用户名:
                    input(type='text' name='username')
                li
                    span 密码:
                    input(type='password' name='password')
                li
                    button(type="submit") 注册
        script.
            if ('#{mistake}') {
                alert('#{mistake}')
            }
            if('#{error}'){
                alert('#{error}')
            }

这是注册log.pug

doctype html
html(lang="en")
    head
        title= blog
        link(rel='stylesheet' href='/css/list.css')
    body
        div(class='list')
           p 登录成功
        script(src='/js/index.js')

这是登录成功模块list.pug

接着便是路由模块

const Router=require('koa-router');
const router=new Router();
const user=require('./routers/router');
router.get('/',async ctx=>{await ctx.render('xt')});//渲染首页
router.post('/log',user.reg);//获取注册模块发送过来的信息
router.get('/log', async ctx=>{await ctx.render('log')});//渲染注册模块
router.get('/reg',async ctx=>{await ctx.render('first')});//渲染登录模块
router.post('/submit',user.log);//获取登录模块发送过来的信息

接着是数据库模块

const mongoose=require('mongoose');
const db=mongoose.createConnection('mongodb://localhost:27017/reg',{useNewUrlParser:true});
mongoose.Promise=global.Promise;
db.on('open',()=>{console.log('连接成功')});
db.on('error',()=>{console.log('连接失败')});
const Schema=mongoose.Schema;
module.exports={Schema,db};//建立reg数据库,到处db和Schema

还有加密模块,因为数据库存储的信息都是要加密的

const crypto=require('crypto');
function fn(password){
    const obj=crypto.createHmac('sha256',key='emmmm');
    const data=obj.update(password);
    return data.digest();
}
exports.crypto=fn;

最后是业务处理

const {db}=require('../database');
const crypto=require('../crypto/jm');
const {Schema}=require('../database');
const userSchema=new Schema({username:String,password:String});
const User=db.model('users',userSchema);//得到操作数据库表的对象
//注册验证函数
exports.reg=async ctx=>{
    let {username,password}=ctx.request.body;
    if(username===''||password===''){
      return  await ctx.render('log',{mistake:'请完善表单信息'})
    }//用户名或者密码为空,重新渲染注册页面并弹出信息
    await new Promise((res,rej)=>{
        User.find({username},(err,data)=>{
            if(err)return rej;//数据库错误返回失败信息
            if(data.length!==0){
                return res('');}//存在相同用户名返回
            const pd=crypto.crypto(password);
            const obj=new User({username,password:pd})
            obj.save((err,data)=>{
                if(err)return err;
                return data;
            })
            return res('注册成功');
        })
    }).then(async data=>{
        if(data){
            await ctx.render('first',{success:'注册成功'});
        }else{
            await ctx.render('log',{error:'注册失败,用户名已存在',status:0});
        }
    },async data=>{
        await ctx.render('log',{error:'注册失败',status:1})
    })
}
//登录验证函数
exports.log=async ctx=>{
    const {username,password}=ctx.request.body;
    if(username===''||password===''){
       return await ctx.render('first',{mistake:'请完善表单信息'})
    }
    await new Promise((res,rej)=>{
        User.find({username},(err,data)=>{
            if(err){return rej;}
            if(data.length===0){
                return rej('用户名不存在');

            }
            if(data[0].password==crypto.crypto(password)){
                return res();
            }
        })
    }).then(async()=>{
        await ctx.render('list')//登录成功
    },async(data)=>{
        if(data){
            await ctx.render('first',{err:'用户名不存在'})
        }else{
            await ctx.render('first',{error:'系统异常'});
        }
    })
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值