当前位置: 首页 > 后端技术 > Node.js

基于节点的登录示例(node-koa-mongoose)

时间:2023-04-03 20:11:50 Node.js

前言这是一个基于节点实现的简单登录示例。对于刚入门node的同学,想多了解一下前端页面是如何向服务层请求->路由处理->数据库的,整个操作->返回结果的过程对同学更有用到页面。本示例基于github上的两个项目(文末有链接)。自己整理重写,希望有需要的同学能够看到。项目源码地址:https://github.com/linwalker/...技术栈节点使用Koa框架,节点7.6及以上版本可直接使用async/await;使用mongoose连接Mongodb数据库并进行交互;前端使用react和antd-design组件;webpack包搭建环境准备运行node.js>=7.6mongodbinstallrobomongoinstall(mongodb可视化工具)mongodb新建一个数据库node-login,并打开;npminstall安装依赖npmrunbuild代码构建nodeapp启动服务可以访问localhost:3003/home项目目录node-login|--components//页面组件|--LoginTab.js|--RegisterTab。js|--controller//路由回调处理|--user-info.js|--models//用户模型|--user.js|--pages//页面js|--home|--home.js|--index.js|--main|--routes//路由|--static//静态文件|--tools//webpack构建文件|--views//页面模板|--.babelrc|--app.js//入口文件|--config.js//配置文件|--package.json入口文件具体介绍--app.jsconstKoa=require('koa');const...constapp=newKoa();//配置控制台日志中间件app.use(convert(koaLogger()));//使用ctx.body解析中间件app.use(bodyParser());//配置服务端模板渲染引擎中间件app.use(views(path.join(__dirname,'./view'),{extension:'ejs'}));//配置静态资源loadingmiddlewareapp.use(convert(koaStatic(path.join(__dirname,'./static'))))mongoose.Promise=global.Promise;mongoose.connect(config.database);//初始化路由中间件app。use(routers.routes()).use(routers.allowedMethods())app.listen(3003);console.log('服务器在prot3003上')服务主要是数据库连接,路由处理,静态文件配置和页面模板渲染配置文件-config.jsmodule.exports={'secrect':'linwalkernodelogindemo',//暂未使用,用于后面的token验证'database':'mongodb://localhost:27017/node-login'//填写Localmongodb连接地址};主要是设置连接mongodb数据的连接地址用户模型——user.js定义了登录注册的用户模型constmongoose=require('mongoose');constSchema=mongoose.SchemaconstUserSchema=newSchema({username:{type:String,unique:true,require:true},password:{type:String,require:true},email:{type:String,}});module.exports=mongoose.model('User',UserSchema);用户模型主要有三个数据,用户名、密码和邮箱。路由路由总入口/routes/index.js导入所有路由,使用koa-router中间件constrouter=require('koa-router')();consthome=require('./home');constmain=require('./main');consteditor=require('./editor');router.use('/home',home.routes(),home.allowedMethods());router.use('/main',main.routes(),main.allowedMethods());router.use('/editor',editor.routes(),editor.allowedMethods());module.exports=router;三个主要的路由是/home、/main/和/editor,主要看/home:constrouter=require('koa-router')();constuserInfoController=require('./../controller/user-info');constrouters=router.get('/',async(ctx)=>{consttitle='loginhome';awaitctx.render('home',{title})}).post('/signup',userInfoController.signUp).post('/signin',userInfoController.signIn)module.exports=routers;home.js的get请求返回首页,两个post请求是注册和登录处理。让我们看一下处理user-info.js的登录请求。constUser=require('./../models/user');模块。exports={asyncsignUp(ctx){...},asyncsignIn(ctx){letresult={success:false,message:'用户不存在'};//从请求体中获取参数const{username,password}=ctx.request.body;//检查用户名是否存在于数据库中{//检查密码是否正确if(password===user.password){ctx.body={success:true,message:'登录成功'}}else{ctx.body={success:false,message:'密码错误'}}}})}}登录请求处理过程是先检查用户名是否存在,再判断密码是否正确。在看下面发起请求的地方登录请求classLoginTabextendsReact.Component{handleSubmit=async(e)=>{e.preventDefault();让values=awaitthis.getFormValues();if(values){fetch('/home/signin',{method:'POST',headers:{'Content-Type':'application/json;charset=utf-8'},body:JSON.stringify(values)}).then(res=>{res.json().then(res=>{Message.info(res.message);if(res.success){location.href='/main';}})})}}getFormValues(){让self=this;returnnewPromise((resolve,reject)=>{self.props.form.validateFields((err,values)=>{if(!err){resolve(values);}else{拒绝(错误的);}})})}render(){const{getFieldDecorator}=this.props.form;return(...

)}}导出默认表单.create()(LoginTab);表单提交按钮绑定了handleSubmit事件,该事件首先获取表单提交数据,然后发起/home/signin的post请求,根据请求结果的成功值决定是否跳转到成功页面。这里用到了antd-design表单组件的相应属性。操作演示演示用户名不存在,密码错误,登录成功。综上,使用了koa框架,主要是路由和ctx上下文处理。没用过的同学可以点开koa2教程看看。这是一篇写的很好的koa入门教程;它使用mongoose操作数据库,涉及到的栗子并不难,就是一个User模型,一个save保存数据和一个findOne查找,看完文档就明白了,或者使用antd-design看这篇文章component备注本例主要参考:项目1项目2