当前位置:首页 >> 网络编程

node.js +mongdb实现登录功能

一、开发环境准备

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

四、拆分路由系统

node.js +mongdb实现登录功能

//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);

五、初始化项目的配置文件

node.js +mongdb实现登录功能

//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 -->视图控制层

node.js +mongdb实现登录功能

//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 = "用户名和密码不存在"
 } 
}

总结