Node.js + Express + MongoDB database functions to achieve the page Register Login

                By Node.js + Express + MongoDB page-registered account and login account functions

Project Preparation:

  1: prepared in advance of a good project page (home page index.html) (login page login.html) (registration page register.html) 

  2: installing third-party template you want to use Node.js

  3: Design Path Design

  4: clarify the functional requirements

  5: Create app.js router.js mgdb.js three js files and public folders and views

effect:

  app.js file is used to turn on the server

  router.js design file for the request path

  mgdb.js file for MongoDB database connection

  public folder is used to store public documents such as: three pages css style file    

  views folder used to store three ready to be used to page

To speak directly on the code:

In app.js file:

 

// imports template
Express the require = var ( 'Express'); 
// introduce a third party module for acquiring data POST request var bodyParser = require('body-parser'); // Load router.js file var router = require('./router.js'); // Create app Ideas were Out = (); // The node_modules and public disclosure documents app.use('/node_modules', express.static('./node_modules/')); app.use('/public', express.static('./public/')); // use template engine with Express app.engine('html', require('express-art-template')); // body-parser configuration app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // The routing service container mounted to app app.use(router) app.listen(3000, function(){ console.log ( 'server starts successfully, and can be accessed by http://127.0.0.1:3000/'); });

In router.js file

 

 

// imports template
var fs = require('fs');
var express = require('express')
// imports mgdb.js file
var Mgdb = require('./mgdb.js')

// 1: Create a container route
var router = express.Router()

@ 2: The router routes routes are mounted to the vessel
/ * Home page * /
router.get('/', function(req,res) {
    res.render('index.html')
})

/*registration page*/
router.get('/register', function(req,res) {
    res.render('register.html')
})

/ * * Login page /
router.get('/login', function(req,res) {
    res.render('login.html')
})
/ * Registration page to submit data POST * /
router.post('/login', function(req,res) {
    // the data stored in the database MogoDB
    // req.body content data is saved
    new Mgdb(req.body).save(function(err) {
        if (err) {
            return res.status(500).send('Server error.')
        }
        res.redirect('/login')
    })
})

/ * Login page POST * /
router.post('/', function(req,res) {
    // get the input data and database data comparison
    var username = req.body.username
    var password = req.body.password
    Mgdb.findOne({username:req.body.username, password:req.body.password}, function(err,ret) {
        if(err) {
            return res.status(500).send('Server error.')
        } else {
            // If the password is incorrect or the account is null ret
            if(ret === null) {
                res.send ( 'account number or password is incorrect')
            } else {
                // If the account password is correct ret return data in the database objects
                // Get the user name rendered to the home page
                var name = ret.username
                res.render('index.html', {
                    name: name
                })
            }
        }
       
    })
})

// 3. Place the router to export
module.exports = router

In mgdb.js file

// imports template
var mongoose = require('mongoose')

// define a schema
Scheme var = mongoose.Schema

1. // connect to the database
// Specify the database connection does not need to exist, when you insert the first data will automatically be created out
mongoose.connect('mongodb://localhost/login')

// 2. Design document structure (table structure)
var userSchema = new Schema({
  username: {
    type: String,
    required: true // must have
  },
  password: {
    type: String,
    required: true
  },
  mobile:{
      type: Number,
      required: true
  }
})

// 4. When we have a model constructor, this constructor can be used for data users to operate a set (CRUD)

// 3. The structure of the document published as a model
// constructor directly export models
module.exports = mongoose.model('Mgdb', userSchema)

  Written after the three major documents, through the implementation of app.js cmd file, the browser can be accessed through the test http://127.0.0.1:3000/

 

The effect is as follows:

 

If you enter a password or user name is incorrect, it would respond account or password is incorrect This function is not just to achieve under the page design

 

This is the basic function of account registration and account login page of the entire site, to achieve a small demo features the whole idea is quite clear. As a positive learning with knowledge of the white front-end, in order to implement the entire small demo, we prepared a good route designed to ensure their own clear ideas about a half hour to write.

 

 

  2019-12-14   19:50:47

Guess you like

Origin www.cnblogs.com/ye16p/p/12038402.html