demo of a simple express+jade+mysql+bootstrap+nodejs

Nodejs With the rapid development of Nodejs, the hottest framework for Nodejs construction is not express. Github It can be proved by 32 K star. Let's build a simple demo with Nodejs as the center, which includes both front and back ends.

Whatever project you develop, it's easy to understand and develop with scaffolding. Simple demo allows you to quickly understand the workflow. Don't talk too much nonsense, start building it!

1. Installation and configuration environment
1.1. Install Node.js and NPM
It is convenient to install Node.js under Windows. Please download and install it yourself. The installation package and source code download address are as follows: This is the case. Installation process has been foolish'NEXT'can be. When the installation is complete, open the command line and enter node-v to return the corresponding version number to indicate that the environment variable configuration is successful.
NPM is a package manager installed with Node.js. The new version of Node.js has integrated npm, so NPM is also installed.

1.2. Create and initialize projects
First, go to your working directory, create a new project directory and open it.

D:\WWW>mkdir nodejs-express-mysql-jade && cd nodejs-express-mysql-jade

Create a package.json file for your project through the npm init command.

D:\WWW\nodejs-express-mysql-jade>npm init

This command will require you to enter some parameters, including the application name, version, etc., you can directly press Enter to set the default value. Note that one of them is entry point:, which is the entry file of the project. You can set it to the name you want, such as app.js or index.js. Here I choose app.js by default.

1.3. Install express and application generator express-generator
Direct installation of generator express-generator through npm

npm install express express-generator -g

Then use express [name] or direct express command to build a project; name is the name of the file you entered, and build in the current directory without filling in.


After building the directory structure:

Then install all dependency packages. If you write the above [name], run npm install after entering the directory under [name]. If you don't write the name, run npm install directly in the current directory.

npm install

1.4. Operating Projects

Running commands

set DEBUG=myapp & npm start

Then open it in the browser http://localhost:3000/ You can see the application on the website.

Of course, it is inefficient to re-execute the command every time the code is updated. Installing nodemon is inefficient.

npm install nodemon -g

Modify package.json:

  "scripts": {
    "start": "set DEBUG=myapp & nodemon ./bin/www"

After that, as long as the file is updated, the server will automatically update and start, and go to the page to refresh directly.

The construction of the first step here is over.

2. Connecting Background

2.1. Install mysql and connect to database

npm install mysql -g

After installing the package, create two new directories in the project root directory as shown in the red box below.

Build a database user locally, and build a user table, then add three fields id, name, age;

Where conf.js:

// MySQL database connection configuration
module.exports = {
    mysql: {
        host: 'localhost', 
        user: 'root',
        password: '',
        database:'user', // The user table previously built is in this database
        port: 3306


var user = {
    insert:'INSERT INTO user(name, age) VALUES(? , ?)',
    update:'UPDATE user SET name = ?, age = ? WHERE id = ?',
    delete: 'DELETE FROM user WHERE id=?',
    queryById: 'SELECT * FROM user WHERE id=?',
    queryAll: 'SELECT * FROM user'

module.exports = user;


// Implementing Interaction with MySQL
var mysql = require('mysql');
var $conf = require('../conf/conf');
// var $util = require('../util/util');
var $sql = require('./userSqlMapping');

// Use connection pools to improve performance
var pool = mysql.createPool( $conf.mysql );

// Simple Encapsulation of Back-to-Back JSON Method
var jsonWrite = function (res, ret) {
    if(typeof ret === 'undefined') {
            msg: 'operation failed'
    } else {

module.exports = {
    add: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            // Get the parameters from the front page
            var param = req.query || req.params;

            // Establish a connection to insert values into the table
            // 'INSERT INTO user(id, name, age) VALUES(0,?,?)',
            connection.query($sql.insert, [, param.age], function(err, result) {
                if(result) {
                    result = {
                        code: 200,
                        msg:'Increase success'
                // Return the result of the operation to the front page in the form of json
                jsonWrite(res, result);
                // Release connection 
    delete: function (req, res, next) {
        // delete by Id
        pool.getConnection(function(err, connection) {
            var id =;
            connection.query($sql.delete, id, function(err, result) {
                if(result.affectedRows > 0) {
                    jsonWrite(res, result);
                    result = {
                        code: 200,
                        msg:'Successful deletion'
                } else {
                    result = void 0;
                jsonWrite(res, result);
    updateUser: function (req, res, next) {
        var param = req.body;
        if( == null || param.age == null) {
            jsonWrite(res, undefined);
        pool.getConnection(function(err, connection) {
            connection.query($sql.update, [, param.age,], function(err, result) {
                // Use pages for jump hints
                // if(result.affectedRows) {
                //     res.render('suc',{
                //         title:'Success Page',
                //         result: result
                //     }; // The second parameter can be used directly in jade
                // } else {
                //     res.render('fail',  {
                //         result: result
                //     });
                // }
                jsonWrite(res, result);
    queryById: function (req, res, next) {
        var id =;                     // In order to piece together the correct sql statement, we need to turn down the integer.
        pool.getConnection(function(err, connection) {
            connection.query($sql.queryById, id, function(err, result) {
                jsonWrite(res, result);
    queryAll: function (req, res, next) {
        pool.getConnection(function(err, connection) {
            connection.query($sql.queryAll, function(err, result) {
                // jsonWrite(res, result);
                    title:'List page',

2.2. Update routing
Edit routes/users.js

var express = require('express');
var router = express.Router();
var userDao = require('../dao/userDao');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
// Adding users
router.get('/addUser', function(req, res, next) {
    userDao.add(req, res, next);
router.get('/addUserMiddle', function(req, res, next) {
        title:'Add user pages'
//View all users
router.get('/queryAll', function(req, res, next) {
    userDao.queryAll(req, res, next);
//Query the specified user
router.get('/query', function(req, res, next) {
    userDao.queryById(req, res, next);
//delete user 
router.get('/deleteUser', function(req, res, next) {
    userDao.delete(req, res, next);
//Update user information'/updateUser', function(req, res, next) {
    userDao.updateUser(req, res, next);

module.exports = router;

2.3. Install bootstrap to add the corresponding view file

Install bootstrap first bower

npm install bower -g

After installing bower, edit the. bowerrc file. The downloaded package can be placed in the corresponding location:

  "directory" : "public/libs"

Install bootstrap package:

bower install bootstrap

Recently, however, bower seems to have been maintained so that bootstrap and jquery packages can be installed with npm.

npm install bootstrap@3 --save
npm install jquery --save

After installation, the package module is not so easy to manage because there is no webpack. So use gulp to pull the package directly to the resource directory public

npm install gulp -g

Build a gulpfile.js file in the same directory as package.json and enter the following code:

var gulp = require('gulp');

gulp.task('moveJquery' , function(){
    return gulp.src('node_modules/jquery/*/*')

gulp.task('moveBootstrap' ,['moveJquery'] ,  function(){
    return gulp.src('node_modules/bootstrap/*/*/*')

On the command line, enter:

gulp moveBootstrap

This brings the package under node_modules to public/libs

Finally, the corresponding files are introduced on layout.jade:

doctype html
        title #{title}
        link(rel='stylesheet', href='/libs/bootstrap/dist/css/bootstrap.min.css')
        block content

Other views are not listed here.

After completing all the work, enter localhost:3000/users/queryAll on the browser to complete all the operations shown in the following figure.

Operation result diagram:

Add users:

Edit user information:

User Information List:

Filtering user information, here is simply written according to id filtering, here does not focus on this:

That's all. It's a good demo for children's shoes that have just touched Nodejs.

Next time, we will continue to improve the front-end tools. Web pack configuration hot update and so on. This way, after updating your code, you can go directly to the page to see the effect, even F5 do not need to press, these details will greatly improve the efficiency of development.

Project address: Demo Just want to understand the process and do not want to build children's shoes clone directly to the local oh. If you have any help, please give me a star ha! uuuuuuuuuuuu

Tags: Javascript npm MySQL JSON SQL

Posted on Mon, 24 Dec 2018 05:18:06 -0500 by LarryK