What is the

Express4. x development common features memo

The function point

  1. Initialize the project
  2. Initialize the global variable configuration
  3. Initialize the template engine
  4. Initializing a Route
  5. Initialize the mysql module
  6. Initialize the log module
  7. Initialize the cookie module
  8. Initialize the session module
  9. Function – file upload module
  10. Function – Mock module
  11. Case – add, delete, change and check users

Initialize the project

NPM install express-generator # Add express-e express4 to the command line. 0-starter initializes the Express project CD Express4. 0-starter YARN # install NPM start # Start # Configure the development environment - Automatically start NPM install node-dev"scripts": {
    "start": "node-dev ./bin/www"} # install -g supervisor"scripts": {
    "start": "supervisor ./bin/www"
}
Copy the code

Initialize the global variable configuration

Referenced in app.js

 // Set the global static variable library
app.locals.globals = require('./config/globals');

// globals.js
module.exports = {
    avatar: {dest: '.. /avatar/'.rename: function (fieldname, filename) {
            return filename.replace(/\W+/g.The '-').toLowerCase() + Date.now()
        }
    },
    baseUrl:'http://127.0.0.1:3000/'
};
Copy the code

Initialize the template engine

After the controller gets the user request, it retrieves the data from the model and invokes the template engine.

The template engine takes data and page templates as input, generates HTML pages, and returns them to the controller, which returns them to the client.

Modify the app. Js

var ejs = require('ejs'); 
app.engine('.html',ejs.__express);  
app.set('view engine'.'html');
Copy the code

Ejs grammar

/ / ejs syntax<% code %> : JavaScript code. <%= code %> : Displays the content with HTML special characters replaced. <% -code %> : Displays the original HTML content. <% -include layout %> Page layout/ / template
<%include commons/header.html%>
<%include commons/footer.html%>

<%= title %>

/ / loopThe < %for(var i=0; i < users.length; i++)  {%>
    <tr>
        <td><%=users[i].id%></td></td>
    </tr>
<% } %>

// js-elseThe < %if(page =="addUser") {} % > < %else} {% > < % % >Copy the code

Initializing a Route

Modify app.js and create router/index.js respectively to add changes

// app.js
var users = require('./routes/users');
app.use('/users', users);

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

var usersDao = require('.. /model/usersDao');
router.get('/'.function(req, res, next) {
  usersDao.queryAll(req, res, function(data){
      res.render('users/list', {
          title:title,
          users: data
      });
  });
});

module.exports = router;
Copy the code

Common operations on the Router

  1. One is to use Res.Render instead of the Jade (EJS) template to handle the View layer display
  2. One is to use res.send to send data requests directly to the web page.
  3. Get Requests req.query.username to obtain parameters.
  4. Post requests req.body.username to get the parameter.
  5. Json returned res. Json ({‘ code ‘:’ success ‘, ‘info: data});
  6. Req (Request) represents client data and is a readable stream.
  7. Res (Response) represents data on the server and is a writable stream. You can get the data you want:
  8. The next function is responsible for passing control to the next middleware. If the current middleware does not terminate the request and next is not called, the request will be suspended and the middleware defined below will not have a chance to execute. The next function is mainly used to ensure that all registered middleware is executed one after another, so we should call next on all middleware, with the exception that we should not call Next if the middleware we defined terminates the request.
// render maps to HTML
res.render('users/one', {title:title,user:user});
// Jump to the page
res.redirect('/users');
// json
res.json({ title: 'express4.0 json' }) 
// send
res.send('<===>some html');
// locals
res.locals.isLogin = req.session.isLogin;
// cookie
res.cookie('name'.'tobi', options);
/ / value
req.params.name  // Value (/user/:name)
req.query.ctime / / values (?,?,?,?,? q=tobi+ferret)
req.param('name') // Value (? Tobi, /user/:name,? Q = tobi + ferret)
req.body.name // Value (post value)
res.redirect('http:// example. com'); 

// Q:Error: Can't set headers after they are sent.
// Cannot send headers because it has already been sent once. When processing an HTTP request, the server sends the request header first, followed by the request content. This error is reported if you try to call res.redirect(), the method that sets the header, after creating a connection that generates a header.
Json ({success: true, message: 'success'}); // return res.json({success: true, message: 'success'});
// Use return before response.

/ / get request
router.get("/doAjax".function(req, res, next) {
    // req receives requests
    var username = req.query.username;
    var password = req.query.password;
    // return to the page
    res.json({
      code: "success".info:
        "The server receives an Ajax GET request for the user name [" +
        username +
        "[the] code +
        password +
        "]"
    });
  });
// Post request:
router.post("/doAjax".function(req, res, next) {
    // req receives requests
    var username = req.body.username;
    var password = req.body.password;
    // return to the page
    res.json({
        code: "success".info:
        "The server received an Ajax POST request for the user name [" +
        username +
        "[the] code +
        password +
        "]"
    });
});
Copy the code

Initialize the mysql module

Create config/server.js configuration file, utils linked database tool file, create models/user.js model query database

Link a database, such as mysql

"Mysql" : "^ 2.15.0", "mysql2" : "^" 1.5.1.Copy the code
// utils
var mysql = require('mysql');
var $conf = require('.. /config/server'); / / database
var utils = {
    // Database link
    pool: function () {
        function extend(target, source, flag) {
            for (var key in source) {
                if (source.hasOwnProperty(key))
                    flag ?
                        (target[key] = source[key]) :
                        (target[key] === void 0 && (target[key] = source[key]));
            }
            return target;
        }
        // Use connection pooling to improve performance
        returnmysql.createPool(extend({}, $conf.mysql)); }}// models/user.js
var $utils = require('.. /utils'); / / tools
var pool = $utils.pool(); // Database link pool
var $sql = require('./usersMapping'); / / SQL statements
pool.getConnection(function(err, connection) {
    connection.query($sql.queryAll, function(err, result) {
        if(result.length){
            callback(result);
        }else{
            result = void 0;
        }
        // jsonWrite(res, result);
        connection.release();
    });
});
Copy the code

Initialize the log module

  1. Log4j1. x Logs errors that occur in a project
  2. Morgan is used to log access
"Morgan" : "~ 1.5.1" "file - stream - rotator" : "~ 0.0.6" log4js ":" "~ 1.0.0"Copy the code

Modify the app. Js

var logger = require('morgan'); // Record access logs
var fs = require('fs');
var fileStreamRotator = require('file-stream-rotator');
var logDir = path.join(__dirname, 'logs');
fs.existsSync(logDir) || fs.mkdirSync(logDir);
var accessLogStream = fileStreamRotator.getStream({
    date_format: 'YYYYMMDD'.filename: path.join(logDir, 'access-%DATE%.log'),
    frequency: 'daily'.verbose: true
});
app.use(logger('combined', {stream: accessLogStream}));
Copy the code

Using a logger

var $utils = require('.. /utils'); / / tools
var logger = $util.logger(); // Log management
logger.info("this is log");// Output logs
Copy the code

Initialize the cookie module

"Cookie - parser" : "~ 1.4.3"Copy the code

Modify the app. Js

var cookieParser = require('cookie-parser'); / / cookie configuration
app.use(cookieParser('this is key')); / / set cookies
Copy the code

Test the cookie

// router
router.get('/cookie'.function(req, res, next) {
    const options = {
      domain:'127.0.0.1'.path:'/'.maxAge: 10 * 60 * 1000.// Cookie validity period
      expires: new Date('2019-02-02'),  // Cookie expiration time
      httpOnly: false.// Whether to obtain only in HTTP requests
      overwrite: false  // Whether overwriting is allowed
    }
    res.cookie('name'.'tobi', options);
    res.send(req.cookies.name);  // Prints the cookie value
});
Copy the code

Initialize the session module

"Express - session", "^ 1.15.6"Copy the code

Modify the app. Js

import serverConfig from './config/global.js'
app.use(session({
  "resave": serverConfig.session.resave,
  "saveUninitialized": serverConfig.session.saveUninitialized,
  "secret": serverConfig.session.secret, // A random string of 128 characters is recommended
  "cookie": serverConfig.session.cookie
}));
Copy the code

The test session

req.session.count = req.session.count || 0; 
var sessionCount = req.session.count++;
Copy the code

Function – file upload module

"Multer" : "^ 1.2.0"Copy the code
// router.js
var multer  = require('multer');
var fs = require("fs");
var upload = multer({ 
    dest: './avator/'.rename: function (fieldname, filename) {
        return filename.replace(/\W+/g.The '-').toLowerCase() + Date.now()
    }
});
router.post('/doUpload',upload.array('image'),function(req, res, next) {
    console.log(req.files[0]);  // Upload file information
    if(undefined == req.files[0]){
        res.json(['failed', {msg:"No file to upload selected!"}]);
        return -1;
    }
    var des_file = "./avatar/" + req.files[0].originalname;
    fs.readFile( req.files[0].path, function (err, data) {
        fs.writeFile(des_file, data, function (err) {
            if( err ){
                console.log( err );
                res.json(['failed', {msg:err}]);
            }else{
                response = {
                    msg:'File uploaded successfully'.filename:req.files[0].originalname,
                };
                res.json(['success', response]); }}); }); });Copy the code

Function – Mock module

"mockjs": "2.x"
Copy the code

Create a mock/index. Js


var Mock = require("mockjs");
var Random = Mock.Random;
var data = Mock.mock({
'results|10': [{
    'id|+1': 1.'username':'@name'.'password':'1234'.'sex':Random.integer(1.2),
    'age':/\d{2}/.'photo':'photo.jpg'.'realname':"@cname()"}}]);console.log(JSON.stringify(data, null.4));
Copy the code

Case: user add, delete, change and check

The mock/ usersmock. js, model/ usersdao.js, model/usersMapping. Js, routes/users.js are included

Making: github.com/wolichuang/…

Attachment: package. Json

{" name ":" express4.0 - learn ", "version" : "0.0.0", "private" : true, "scripts" : {" start ": "Node - dev. / bin/WWW"}, "dependencies" : {" body - the parser ":" ~ 1.16.0 ", "co" : "~ 4.6.0", "cookie - parser" : "~ 1.4.3," "debug" : "~ server", "ejs" : "~ 2.5.5", "express" : "~ 4.14.1", "express - session" : "^ 1.15.6", "file - stream - rotator" : "^ 0.2.0 mockjs", "" :" ^ -beta3 1.0.1 ", "Morgan" : "~ 1.7.0", "multer" : "^ 1.2.0", "mysql" : "^ 2.15.0", "mysql2" : "^ 1.5.1 node -", "dev" : "^ 3.1.3", "serve - the favicon" : "~ 2.3.2", "log4js" : "~ 1.0.0}}"Copy the code