node.js +mongdb实现登录功能
程序员文章站
2022-03-18 17:31:19
一、开发环境准备npm init -y //初始化仓库npm i koa koa-router -s //安装koa和路由模块npm i nodemon -s二、开启node服务//index.jsc...
一、开发环境准备
npm init -y //初始化仓库 npm i koa koa-router -s //安装koa和路由模块 npm i nodemon -s
二、开启node服务
//index.js const koa = require("koa"); const router = require("koa-router")(); const app = new koa(); router.get("/",async ctx=>{ ctx.body = "我是首页" }) app.use(router.routes()); app.listen(8080);
三、配置art-template
3-1 安装依赖
npm install koa-art-template art-template -s
四、拆分路由系统
//routers-index.js const router = require("koa-router")(); router.get("/", async ctx => { await ctx.render('index'); }) module.exports = router;
//index.js const koa = require("koa"); const router = require('./routers/index.js'); const render = require('koa-art-template'); const app = new koa(); const path = require("path"); render(app, { root: path.join(__dirname, 'views'), extname: '.html', debug: process.env.node_env !== 'production' }); app.use(router.routes()); app.listen(8080);
五、初始化项目的配置文件
//init-config.js const path = require("path"); const render = require('koa-art-template'); const router = require('../routers/index'); function initconfig(app) { // process.cwd()可以读取项目的路径 render(app, { root: path.join(process.cwd(), 'views'), extname: '.html', debug: process.env.node_env !== 'production' }); app.use(router.routes()); } module.exports = initconfig;
//index.js const koa = require("koa"); const app = new koa(); let initconfig = require('./init/config'); initconfig(app); app.listen(8080);
六、mvc设计项目结构
model -->数据层 views -->视图层 controllers -->视图控制层
//routers--index.js const router = require("koa-router")(); const controllers = require("../controllers"); // 只写文件名默认会读取文件里的index.js router.get("/", controllers.index) module.exports = router;
//controller--index.js let index = async ctx=>{ await ctx.render('index'); } module.exports = { index }
七、获取post传值
//1.安装依赖 npm i koa-bodyparser -s
//2.进行项目的配置 var koa = require('koa'); var bodyparser = require('koa-bodyparser'); var app = new koa(); app.use(bodyparser()); app.use(async ctx => { //3.取值 ctx.request.body ctx.body = ctx.request.body; });
八、连接数据库
npm i mongoose -s
//models --db.js const mongoose = require('mongoose'); mongoose.connect( 'mongodb://127.0.0.1:27017/studentmanage', {usenewurlparser: true},(err)=>{ if(err) throw err; console.log("database连接成功") }); module.exports = mongoose;
//models --user.js var mongoose = require('./db'); var userschema = new mongoose.schema({ name:string, pwd:string }) var user = mongoose.model('user',userschema,'user'); module.exports = user;
//controllers -- index.js let dologin = async ctx=>{ let {user,pwd} = ctx.request.body; let data = await usermodel.find({name:user,pwd}); console.log(data); // 数据库中有对应的用户名密码则数组有东西,没有则数组没东西 if(data.length>0){ /* 登录成功 */ ctx.body = "登录成功" }else{ ctx.body = "用户名和密码不存在" } }
总结
到此这篇关于node.js +mongdb实现登录功能的文章就介绍到这了,更多相关node.js mongdb实现登录内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!