Create a project

Environment: Node14.17, Express4.16

Quick start

express app
cd app
npm init -y
npm run start
Copy the code

At this point, an application Web project containing the deployment service is created.

File directory structure

App │ app. Js// Application creation/configuration│ ├─bin │ WWW// Deploy the HTTP server│ │ ├ ─ public │ ├ ─ images ├ ─ javascripts │ └ ─ stylesheets │ style.css. CSS │ ├ ─ routes │ index. The js │ users. Js │ └ ─ views error. The jade index.jade layout.jadeCopy the code

routing

In addition to the default route, additional routes need to be added.

Define the routing

Add route index.js to the routes folder.

/* routes>index.js */

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

router.get('/index'.function (req, res, next) {  
    // response something
});

module.exports = router;
Copy the code

Routing view

The routing page is presented by the response view (HTML), and there are many response modes. Here we modify the original views file structure, and manage different view files respectively:

Views ├─ HTML │ ├─ EJS │ ├─ Jade │ ├.jade │ Layout.jadeCopy the code

To match different types of view files, the routing module has been modified accordingly:

│ Routes ├─file │ Index.js │ users.js ├─ Engine │ index.js │ users.jsCopy the code

The HTML file

If your page is simple and static, you can choose to render the routed page by responding directly to the HTML file.

HTML to render
<! -- views>html>index.html -->

<! DOCTYPEhtml>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
        <title>HTML</title>
    </head>
    <body>
        <h1>A normal HTML page</h1>
    </body>
</html>
Copy the code
Routing response
/* routes>file>index.js */

var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/'.function (req, res, next) {
    const file = fs.readFileSync('views/html/index.html'.'utf-8') // The absolute path of fs and the encoding of the file are important
    res.send(file)
});

module.exports = router;
Copy the code

HTML pages can be rendered directly without any configuration of a template engine.

A template engine

A template engine allows you to pass dynamic control view content through variables, and different template engines provide different concise syntax, each with its own advantages.

The Express-Generator uses JADE as the default templating engine.

Installing the Template Engine (EJS)
npm i ejs
Copy the code
Mount the template engine
/* app.js */

app.set('views', path.join(__dirname, `views/ejs`)); // Import view files in batches
app.set('view engine'.'ejs'); // Mount the template engine
Copy the code
Template view file
<! -- views>ejs>index.ejs --> <h2><%= template %></h2> <p> Welcome to <%= index %></p>Copy the code
Routing response

Res.render (view,data) is used in the route response. This API passes in the view file name and the passed data, and finally returns an HTML.

/* routes>file>index.js */

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

router.get('/index'.function (req, res, next) {
    res.render('index', {
        template: 'EJS '.message: 'index'}); });module.exports = router;
Copy the code
Custom Template Engine (NUJ)

Customize a template engine that can design template syntax according to your preferences and parse it to HTML when rendering accordingly; You can also do nothing and return the contents of the file.

/* app.js */

app.set('views', path.join(__dirname, `views/html`));
app.set('view engine'.'nuj');

// setup nuj engine
app.engine('nuj'.function (filePath, options, callback) {
    // Handle file contents...
    fs.readFile(filePath, function (error, content) {
        if (error) return callback(new Error(error))
        var renderContent = content.toString().replace('%title%'.'<title>'+options.title+'</title>')
        return callback(null, renderContent)
    })
})
Copy the code

Routing mount

Note that if the path /index has been defined in routes>*>index.js, do not set the path repeatedly when mounting.

File Response route

/* app.js */

app.use('/'.require('./routes/file/index'));  
// app.use('/about', require('./routes/file/index')); // Set the path repeatedly
Copy the code

Render template engine routing

/* app.js */

app.use('/'.require('./routes/engine/index'));  
Copy the code

Routing matching

.