Node.js+Express+MongoDB database for web page registration and login

Posted by widget on Mon, 16 Dec 2019 04:44:41 +0100

Implement web-based account registration and login through Node.js + Express + MongoDB

Project preparation:

1: Prepare the project page (index.html for the first page) (login.html for the login page) (register.html for the registration page)

2: Third-party templates needed to install Node.js

3: Design Path Design

4: Clear up functional requirements

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

Effect:

The app.js file is used to open the server

router.js file for request path design

The mgdb.js file is used to connect to the MongoDB database

The public folder is used to store public files such as css-style files for three pages.

The views folder is used to store three pages ready for use

Speak directly to the code:

In the app.js file:

 

// Introducing templates
var express = require('express');
// Introducing a third-party module to obtain POST request data var bodyParser = require('body-parser'); // Load router.js file var router = require('./router.js'); // Create app var app = express(); // Publish the files of node_modules and public app.use('/node_modules', express.static('./node_modules/')); app.use('/public', express.static('./public/')); // Use Engine Template with Express app.engine('html', require('express-art-template')); // body-parser configuration app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); // Mount the routing container into the app service app.use(router) app.listen(3000, function(){ console.log('Server started successfully, you can http://127.0.0.1:3000/for access'; });

In the router.js file

 

 

// Introducing templates
var fs = require('fs');
var express = require('express')
// Introducing the mgdb.js file
var Mgdb = require('./mgdb.js')

// 1:Create a Routing Container
var router = express.Router()

// 2: Mount routes in the router routing container
/*Home page*/
router.get('/', function(req,res) {
    res.render('index.html')
})

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

/*Logon Page */
router.get('/login', function(req,res) {
    res.render('login.html')
})
/* Registration Page Submission Data POST*/
router.post('/login', function(req,res) {
    // Save data in a MoogoDB database
    // req.body is the stored data content
    new Mgdb(req.body).save(function(err) {
        if (err) {
            return res.status(500).send('Server error.')
        }
        res.redirect('/login')
    })
})

/*Logon Page POST*/
router.post('/', function(req,res) {
    // Get data after entering data to compare with database data
    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 {
            // ret is null if account or password is incorrect
            if(ret === null) {
                res.send('Error in account or password')
            } else {
                // If the account password ret correctly returns the data object in the database
                // Get this username to render on the home page
                var name = ret.username
                res.render('index.html', {
                    name: name
                })
            }
        }
       
    })
})

// 3. Export router s
module.exports = router

In the mgdb.js file

// Introducing templates
var mongoose = require('mongoose')

// Define a schema
var Schema = mongoose.Schema

// 1. Connect to the database
// The database specified for the connection does not need to exist and will be created automatically when you insert the first data
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. Once we have a model constructor, we can use it to manipulate the data in the users set (add, delete, check)

// 3. Publish the document structure as a model
// Direct Export Model Constructor
module.exports = mongoose.model('Mgdb', userSchema)

After writing the three main files, execute the app.js file via cmd and test it in the browser through http://127.0.0.1:3000/ access

 

The results are as follows:

 

If you fill in your password or user name incorrectly, you will respond that your account or password is incorrect. There are no design pages for any of the functions you want to implement.

 

This is the basic function of account registration and account login on the whole website page, and the idea of implementing the whole small demo function is clear.As a little white learning front-end knowledge, in order to achieve the whole small demo, we have prepared the routing design in advance to ensure their ideas are clear, and wrote about an hour and a half.

 

 

  2019-12-14   19:50:47

Topics: Javascript Database Mongoose MongoDB JSON