Initial experience of nodejs Express framework

Posted by Drayton on Sat, 11 Dec 2021 11:17:06 +0100

1, Introduction to Express framework

In the previous Node basics, we learned Node JS, although you know how to use Node The HTTP module in JS can develop Web applications, deal with static resources, deal with dynamic resources, request distribution (routing), etc. it can also make developers understand the HTTP protocol more clearly, but it is complex to use and the development efficiency is low.

npm provides a large number of third-party module packages, including many Web frameworks. We don't need to invent the wheel repeatedly, so we choose to use it Express As a development framework, it is the most stable and widely used, and node JS is the only Web development framework officially recommended. In addition to providing a higher-level interface for the http module, it also implements many functions, including:

  • Static file service;

  • Routing control;

  • Template resolution support;

  • Dynamic view;

  • User session;

  • CSRF protection;

  • Error controller;

  • Access log;

  • Cache;

  • Plug in support.

Official website: Express - based on node JS platform web application development framework - Express Chinese document | express Chinese network

express is a third-party package based on the built-in core http module, which focuses on the construction of web server.

2, Use Express to build the Hello world program of the server

  • First, create a directory named myapp, enter and run yarn init -y (or npm init -y) on the command line.

  • Install the express package using yarn address Express -- save (or npm install express --save);

  • Secondly, in the myapp directory, create a file named app JS and copy the code in the following example.

// 1. Introduce the express module and create the express object
const express = require('express');
const app = express();

// 2. Write the method of processing the request to respond to the request
app.get('/', (req, res) => {
    // The code here is executed when the browser requests / with get,  
    // This function is used to process the browser's get request for /
    // The first parameter req is the request header object, which contains the request header information
    // The second parameter, res, is used to respond
    console.log(req);
    
    res.send('Hello World!222');
});

// 3. Listening port
app.listen(3000, () => {
    //The code here is executed once when the server is started
    console.log('Example app listening on port 3000!')
});

Use node app JS start the application and access http://localhost:3000/ You can see the effect.  

3, Processing of get requests using Express

3.1. Return to page

Create a new views folder under myapp directory and put it into register HTML page.

register. In HTML:

<h1>Registration page 11</h1>
<hr>
<form action="/register" method="POST" enctype="application/x-www-form-urlencoded">
    <p>
        user name:<input type="text" name="username" placeholder="enter one user name...">
    </p>
    <p>
        Email:<input type="text" name="email" placeholder="Please enter email...">
    </p>
    <p>
        password:<input type="password" name="password">
    </p>
    <p>
        Confirm password:<input type="password" name="repwd">
    </p>
    <p>
        <input type="submit" value="Registration submission">
    </p>
</form>

On app JS:

const express = require('express');
const app = express();

// 1. Introducing fs and path modules
const fs = require("fs");
const path = require("path");

// 2. Handle get requests from / register
app.get('/register', (req, res) => {
    //Read the page content and return to this page
    let pathName = path.join(__dirname, 'views', "register.html");
    const regPage = fs.readFileSync(pathName, "utf-8");
    res.send(regPage);
});

app.listen(3000, () => {
    console.log('Example app listening on port 3000!')
});

3.2. Get query parameters

app.get('/index', (req, res) => {
    let ret = req.query   // Get an object
    res.send(ret.curPage);

    //You can pass in query parameters when requesting:
    //http://localhost:3000/index?curPage=3&perPage=10
});

4, post request processing using Express

4.1. post request processing format

app.post('/register', (req, res) => {
    //In the callback function, you can obtain the request parameters (the information filled in by the user on the page) and process them
    res.send("post---");
});

4.2. Obtain request parameters

We use the third-party package body parser to handle request parameters more easily and professionally

First, install body parser in the project directory:

Yarn add body parser or NPM install body parser

Get request parameters using body parser:

// 1. Introducing body parser
const bodyParser = require('body-parser')

// 2. Add the bodyParser function to the project app
// parse application/x-www-form-urlencoded for normal page submission
app.use(bodyParser.urlencoded({ extended: false }))  //false the received value is a string or array, and true is any type
// parse application/json    
app.use(bodyParser.json())   // Parsing json format

// 3. Get the request parameter req in the interface body
app.post('/register', (req, res) => {
    // In the callback function, you can obtain the request parameters (the information filled in by the user on the page)

    // Get request parameters
    console.log(req.body);
    
    // After obtaining the request parameters, you can process these request parameters here, such as saving them to the database (we will learn database knowledge later)

    res.send("post ok");
});

5, Redirect to another interface

Generally, after successful registration, you can jump to the login page, which is redirection

We use res.redirect('/login'); To jump to another interface for processing

// Add interface for login page
app.get('/login', (req, res) => {
    //Read the page content and return to this page
    let pathName = path.join(__dirname, 'views', "login.html");
    const loginPage = fs.readFileSync(pathName, "utf-8");
    res.send(loginPage);
});

app.post('/register', (req, res) => {
    // In the callback function, you can obtain the request parameters (the information filled in by the user on the page)

    // Get request parameters
    console.log(req.body.username);
    
    // Generally, after successful registration, you can jump to the login page, which is redirection
    res.redirect('/login');   // Redirect to the '/ login' interface, and the corresponding interface function will be executed
});

6, The all() method combines different ways of the same request path

For the above case / register request, there are two methods: GET and POST. Express provides the all() method of merging and writing interfaces:

app.all('/register',(req, res) => {
    let method = req.method
    if(method==='GET'){
        //Read the page content and return to this page
        let pathName = path.join(__dirname, 'views', "register.html");
        const regPage = fs.readFileSync(pathName, "utf-8");
        res.send(regPage);
    }else if(method==='POST'){
        console.log(req.body.username);
        
        // Generally, after successful registration, you can jump to the login page, which is redirection
        res.redirect('/login');    
    }
    
})

7, Get static resources using Express

const express = require('express');
const app = express();


// Get static resources
// app.use(express.static("public"))  
// "Public" indicates that static resources are specified to be found under the local public 
// Request: localhost: 3000 / images / 01 jpg  


// If you want to add a prefix to the requested path
app.use("/static", express.static("public"))
// localhost:3000/static/images/01.jpg / / there may be a delay. If there is a delay, try restarting the server or browser


app.listen(3000, () => {
    console.log('Example app listening on port 3000!')
});

8, Rendering template pages using Express

We use the art templates template engine

Document URL: Express - art-template

Before use, you need to install art template and express art template

Yarn add art template or NPM install art template
Yarn add express art template or NPM install express art template

Create a new index. In the views directory html

// 1. Modify the template engine to html and import express art template
app.engine('html', require('express-art-template'));
// 2. Set the operation mode to production mode
// production mode
// Development development model
app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
});
// 3. Set the template storage directory to the views folder
app.set('views', path.join(__dirname, 'views'));
// 4. Set the engine suffix to html
app.set('view engine', 'html');

app.get('/', (req, res) => {
    res.render('index') //Return the template through render
});

9, Use of art templates template engine

Use syntax: Syntax - Art template

We can transfer data from the back-end interface to the front-end page, which is why we use the template engine.

app.engine('html', require('express-art-template'));
app.set('view options', {
    debug: process.env.NODE_ENV !== 'production'
});
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

app.get('/', (req, res) => {
    let data = {
        user:{
            id:1,
            name: "Jack",
            age:18,
            job: "coder"
        },
        books:["<Journey to the West", "<Romance of the Three Kingdoms","<A dream of Red Mansions", "<Outlaws of the marsh"],
        num1:20,
        num2:30
    }
    res.render('index', data);   // Pass data into index HTML page.
});

Index. Under views In HTML:

<body>
    <h1>This is the home page</h1>
    <hr>
    <div>{{ user.id }}</div>
    <div>{{ user.name }}</div>
    <div>{{ user.age }}</div>
    <div>{{ user['age'] }}</div>
    <ul>
        {{each books}}
        <li>{{$index}},{{$value}}</li>
        {{/each}}
    </ul>
    <p>num1 and num2 The larger number is: {{num1>num2?num1:num2}}</p>
    {{ if user.name === "Jacka"}}
        <p>{{ user.name }}What is your age{{ user.age }}</p>
    {{/if}}
</body>

A similar template engine is the ejs template engine EJS -- embedded JavaScript template engine | EJS Chinese document

10, Use routing in projects

In the project, we will not write the routing interface directly in the project entry file.

Create a new routes folder under the project folder and a new passport js:

// Extract route
const express = require('express');
const router = express.Router();
const fs = require("fs");
const path = require("path");


router.get('/login', (req, res) => {
    //Read the page content and return to this page
    let pathName = path.join(__dirname, '../views', "login.html");
    const loginPage = fs.readFileSync(pathName, "utf-8");
    res.send(loginPage);
});


router.all('/register',(req, res) => {
    let method = req.method
    if(method==='GET'){
        //Read the page content and return to this page
        let pathName = path.join(__dirname, '../views', "register.html");
        const regPage = fs.readFileSync(pathName, "utf-8");
        res.send(regPage);
    }else if(method==='POST'){
        console.log(req.body.username);
        
        // Generally, after successful registration, you can jump to the login page, which is redirection
        res.redirect('/login');    
    }
    
})

module.exports = router

In the project entry file app JS:

const express = require('express');
const app = express();

// 1. Introduce the corresponding routing module
const passportRouters = require('./routes/passport');


var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


// 2. Add written route to app
app.use(passportRouters)


app.listen(3000, () => {
    console.log('Example app listening on port 3000!')
});

11, Tick function before processing request

This function is first understood here and then used in the project.

If you want to execute some code before executing the function that processes the request, such as verifying whether you have logged in.

It can be found in app use(utils.checkLogin, routers); Add a function before

New utils folder, new index JS file:

function checkLogin(req, res, next){
    console.log("The code here will be executed before executing the interface code");


    next();  //Jump directly into the requested interface execution code
}

module.exports = {
    checkLogin
}

In the project entry function app JS:

// Use routing in projects
const express = require('express');
const app = express();

// 1. Introduce corresponding tool module
const utils = require('./utils/index.js');

const passportRouters = require('./routes/passport');


var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


// 2. Add the function executed before executing the interface function
app.use(utils.checkLogin, passportRouters)


app.listen(3000, () => {
    console.log('Example app listening on port 3000!')
});

Effect: before executing each interface under routes, the code in the checkLogin function will be executed.

Application: this can be used to verify login in the project later.

Topics: Javascript node.js Front-end