Node+Express+MongoDB实现登录注册功能实例实现登录注册功能实例
注入注入MongoDB 依赖依赖
var mongoose = require("mongoose");
由于需要进行表单处理,需要用到bodyParser中间件
bodyParser模块来做文件解析,将表单里的数据进行格式化
var bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
登录后将用户信息保存下来,需要使用session中间件,它依赖cookieParser中间件
var cookieParser = require('cookie-parser');
var session = require('express-session');
ar mongoStore = require('connect-mongo')(session);
var dbUrl = 'mongodb://localhost/express';
app.use(cookieParser());
app.use(session({
secret:'express',
store: new mongoStore({
url: dbUrl,
collection: 'sessions'
})
}));
使用jade模板
layout.jade
doctype html
html
head
meta(charset='utf-8')
title #{title}
include ./includes/head
body
include ./includes/header
block content
head.jade
link(href='css/main.css', rel='stylesheet')
link(href="/libs/bootstrap/dist/css/bootstrap.min.css" rel="external nofollow" , rel="stylesheet")
script(src="/libs/jquery/dist/jquery.min.js")
script(src="/libs/bootstrap/dist/js/bootstrap.min.js")
header.jade
.container
.row
.page-header
h1 #{title}
.navbar.navbar-default.navbar-fixed-bottom
.container
if user
p.navbar-text.navbar-right
span 欢迎你,#{user.name}
span |
a.navbar-link(href="/layout" rel="external nofollow" ) 退出登录
else
p.navbar-text.navbar-right
a.navbar-link(href="/signup" rel="external nofollow" , data-toggle="modal", data-target="#signupModal") 注册
span |
a.navbar-link(href="/login" rel="external nofollow" , data-toggle="modal", data-target="#signinModal") 登录
signup.jade