This article mainly introduces the login registration function of Node + Express + MongoDB. If you need it, refer to this article to introduce the login registration function of Node + Express + MongoDB, for more information, see
Inject MongoDB Dependencies
var mongoose = require("mongoose");
Because form processing is required, bodyParser middleware is required.
The bodyParser module parses files and formats the data in the form.
var bodyParser = require("body-parser"); app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: true }));
After logging on, save the user information and use session middleware. It depends on cookieParser middleware.
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' })}));
Use jade Template
Layout. jade
doctype htmlhtml 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 welcome, # {user. name} span |. navbar-link (href = "/layout" rel = "external nofollow") log out and log on to else p. navbar-text.navbar-right. navbar-link (href = "/signup" rel = "external nofollow", data-toggle = "modal", data-target = "# signupModal") registers span |. navbar-link (href = "/login" rel = "external nofollow", data-toggle = "modal", data-target = "# signinModal") login
Signup. jade
Include .. /layout block content form. form-horizontal (role = "form", method = "POST", action = '/user/signup '). form-group label. col-sm-2.control-label (for = "signupName") user name. col-sm-10 input # signupName. form-control (type = "text", name = "user [name]", placeholder = "enter user name "). form-group label. password for col-sm-2.control-label (for = "signuppassword. col-sm-10 input # signuppassword. form-control (type = "password", name = "user [password]", placeholder = "Enter password "). form-group label. col-sm-2.control-label (for = "signupemail") mailbox. col-sm-10 input # signupemail. form-control (type = "email", name = "user [email]", placeholder = "input email "). form-group. col-sm-offset-2.col-sm-10 button. btn. btn-default (type = "submit") to complete registration
Configure routes
Login registration page
// Register the app on the page. get ('/signup', function (req, res) {res. render ('signup', {title: 'registration'}) ;}); // login page app. get ('/login', function (req, res) {res. render ('login', {title: 'login '});});
Registration Function
// Register a single app. post ('/user/signup', function (req, res) {var _ user = req. body. user; User. findOne ({name: _ user. name}, function (err, user) {if (err) {console. log (err);} if (user) {return res. redirect ('/login');} else {var user = new User (_ user); user. save (function (err, user) {if (err) {console. log (err); res. redirect ('/signup');} console. log ('registration successful -- user name: '+ user); res. redirect ('/login ');});}});});
Logon
// Login form app. post ('/user/login', function (req, res) {var _ user = req. body. user; var name = _ user. name; var password = _ user. password; User. findOne ({name: name}, function (err, user) {if (err) {console. log (err);} if (! User) {return res. redirect ('/signup');} user. comparePassword (password, function (err, isMatch) {if (err) {console. log (err);} if (isMatch) {req. session. user = user; // the user name is saved to the console in the session. log ('logon successful -- user name: '+ user); return res. redirect ('/');} else {return res. redirect ('/lgoin ');}});});});
Log out
App. get ('/layout', function (req, res) {delete req. session. user; // delete app. locals. user; // Delete the global variable user. Otherwise, click to log out and the page does not change res. redirect ('/');});
Log on to the registered Database
Connect to database
Mongoose. connect ("mongodb: // localhost/express"); // connect to the database
Schema Definition
Data Update and search, and password Addition
// Schemas/user. jsvar mongoose = require ('mongoose'); var bcrypt = require ('bcrypt'); var SALT_WORK_FSCTOR = 10; // The greater the computing strength, the more difficult it is to crack var UserSchema = new mongoose. schema ({name: {unique: true, type: String}, password: String, email: String, meta: {createAt: {type: Date, default: Date. now ()}, updateAt: {type: Date, default: Date. now () }}); // judge UserSchema every time data is stored. pre ('save', function (next) {var user = this; if (this. isNew) {// data is new data this. meta. createAt = this. meta. updateAt = Date. now ();} else {this. meta. updateAt = Date. now ();} // Add the password to salt bcrypt. genSalt (SALT_WORK_FSCTOR, function (err, salt) {if (err) {return next (err);} bcrypt. hash (user. password, salt, function (err, hash) {if (err) {return next (err);} user. password = hash; next () ;}); UserSchema. methods = {comparePassword: function (_ password, cb) {bcrypt. compare (_ password, this. password, function (err, isMatch) {if (err) {return cb (err);} cb (null, isMatch) ;}}; UserSchema. statics = {fetch: function (cb) {return this. find ({}). sort ('meta. updateAt '). exec (cb) ;}, findById: function (id, cb) {return this. findOne ({_ id: id }). exec (cb )}};
module.exports = UserSchema;
Model compilation model
// Models/user. jsvar mongoose = require ('mongoose'); // mode var UserSchema = require ('.. /schemas/user'); // compile the Model var user = mongoose. model ('user', UserSchema); module. exports = User;
Portal file injection
// App. jsvar User = require ('. /models/user'); app. set ('view engine ', 'jade'); // jade template engine app. set ("views ",". /views/pages/"); // view root directory var serveStatic = require ('serve-static '); // static file processing app. use (serveStatic ('public'); // path: public
Authentication Middleware
Get the session user name, store it in locals, and expose it to the view for use. That is, the user can be obtained in header. jade.
app.use(function (req, res, next) { var _user = req.session.user; app.locals.user = _user; return next();});
The above is the details of the Code for implementing the login registration function (Node. js + Express + MongoDB). For more information, see other related articles in the first PHP community!