Node+expressJs登录验证 一

看到网上一大堆就是用expressJS命令生成项目也叫入门的教程真的伤不起,而且很多不适合现在node或expressJs版本,这篇是根据了不起的nodejs书籍例子而写,书中的这个例子也存在问题,就是模板引擎的编译方法变成not a function了,也找过原因,实在太浪费时间,全部都换成最新的版本,由于书中的例子依赖各个node模块实在太旧,对比新版本的API变化好大,先贴出packjson.json

{
  "name": "node-mongodb-auth",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "express-session": "^1.13.0",
    "gulp": "^3.9.1",
    "gulp-nodemon": "^2.0.6",
    "jade": "~1.11.0",
    "mongodb": "^2.1.7",
    "morgan": "~1.6.1",
    "node-sass-middleware": "0.8.0",
    "serve-favicon": "~2.3.0"
  }
}

使用express命令生成项目

$ nvm use 5.3
$ mkdir auth
$ express --git --css sass
$ npm install
$ npm install mongodb --save

由于是要深入的学习,先把express命令生成的代码全删掉

$ rm -rf public/ routes/ views/ bin/ app.js 
$ mkdir views

创建app.js

/**
 * Created by huangyanxiong 
 */
var express = require('express');  
var app  = express();  
var cookieParser = require('cookie-parser');  
var bodyParser = require('body-parser');  
var session = require('express-session');  
var MongoClient = require('mongodb').MongoClient;  
var ObjectID = require('mongodb').ObjectID;  
var assert = require('assert');

app.use(bodyParser());

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());  
app.use(cookieParser());  
//session
app.use(session({  
    secret: 'keyboard cat',
    saveUninitialized: true,
    resave: true
}));

app.set('views', 'views');

//view
app.set('view engine', 'jade');

//layout
app.set('view options',{layout:false});


//连接mongodb

var url = 'mongodb://localhost:27017/my-website';  
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {  
    assert.equal(null, err);
    console.log("Connected correctly to server");

    //创建集合
    app.users = db.collection('users');

    db.ensureIndex('users','email', function (err) {
        if (err)throw err;
        db.ensureIndex('users','password', function (err) {
            if (err)throw err;
            console.log('ensureIndex');

            //监听端口
            app.listen(3000, function () {
                console.log('listen 3000');
            });
        });
    });

});


//注册一个公共中间件
app.use(function (req,res,next) {  
    console.info(req.session.loginedIn);
   if (req.session.loginedIn){
       res.locals.authenticated = true;
       app.users.find(ObjectID.createFromHexString(req.session.loginedIn)).toArray(function (err,result) {
           console.info(result);
           if (err)return next(err);
           res.locals.me = result[0];
           next();
       })
   }else{
       res.locals.authenticated = false;
       next();
   }
});

//route
app.get('/', function (req,res) {  
    res.render('index');
});


app.get('/login/:signupEmail', function (req,res) {  
   res.render('login',{signupEmail:req.params.signupEmail});
});

app.get('/login', function (req,res) {  
    res.render('login');
});
///get sign up视图
app.get('/signup',function (req,res) {  
    res.render('signup');
});



//post sign up 注册
app.post('/signup', function (req,res) {  
    console.info(req.body);
   app.users.insertOne(req.body, function (err,result) {
       if (err)return next(err);
       console.info(result.ops[0].email);
       res.redirect('/login/'+result.ops[0].email);
   })
});

app.post('/login', function (req,res) {  
    app.users.find({email:req.body.user.email,password:req.body.user.password}).toArray(function (err,result) {
        if (err) return next(err);
        if (!result) return res.send(`<p>user not found, go back try again`);
        req.session.loginedIn = result[0]._id.toString();
        res.redirect('  /');
    })
});

app.get('/logout', function (req,res) {  
    req.session.loginedIn = null;
    res.redirect('/');
});

创建模板文件

views/layout.jade

//
   Created by huangyanxiong
doctype html  
html  
    head
        title Mongodb first example
        body
            h1 my first mongodb app
            hr
            block body

views/index.jade

//
   Created by huangyanxiong

extends layout  
block body  
    if (authenticated)

        p welcome back #{me.first}
        a(href="/logout") Logout
      else
        p Welcome new visitor #{authenticated}
        ul
            li: a(href="/login") Login
            li: a(href="/signup") Signup

views/login.jade

//
   Created by huangyanxiong
extends layout  
block body  
    if (signupEmail)
        p configurations on sign up ! below
    form(action="/login" method="post")
        fieldset
            legend login in
            p
                label email
                input(name="user[email]" type="text" value=signupEmail)
            p
                label password
                input(name="user[password]" type="text")
            p
                button submit
            p
                a(href="/") Go back

views/signup.jade

//
   Created by huangyanxiong on 16-2-18.

extends layout  
block body  
    form(action="/signup",method="post")
        fieldset
            legend Sign up
            p
                label first
                input(name="first",type="text")
            p
                label last
                input(name="last" type="text")
            p
                label email
                input(name="email" type="text")
            p
                label password
                input(name="password" type="password")
            p
                button submit
            p
                a(href="/") Go back

使用Gulp自动重启Node进程

参考

启动

$ export DEBUG=express:*
$ gulp serve

问题

TypeError: Cannot read property '_id' of undefined.

由于没有注册body-parser中间件

app.use(bodyParser());  

总结

你的欣赏是我最大的动力

Yanxiong Huang

My name is Yanxiong Huang. graduated from Nanyang middle school.Love Linux,familiar with Node.js,Docker,Serverless... and more Web technology.Contact Me:QQ 31356617;Email:huangaynxiong2013@gmail.com

guangzhou,china http://www.myfreax.com

乐在分享