Posted in Javascript onJune 18, 2020
一、开发环境准备
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实现登录内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!
node.js +mongdb实现登录功能
- Author -
ITHERS声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@