A brief discussion on the types of node.js middleware

A brief discussion on the types of node.js middleware

Overview

Node middleware is the function of encapsulating http requests in the program. Node middleware is executed in the pipeline. Middleware sits on top of the client/server operating system and manages computer resources and network communications.

Middleware serves the main logical business and can be divided into: application-level middleware, routing-level middleware, built-in middleware, third-party middleware, and error-level middleware.

1. Application-level middleware

Each middleware calls a function and needs to be used with other middleware or routing.

server (function) intercepts all routes

server.use('/reg', function); intercept specific routes

const express = require('express');
var server = express();
server.listen(3000);
//Middleware interception registration route/reg
server.use('/reg',(req,res,next)=>{
    console.log('Registration verification');
    next();
});

server.use('/login',(req,res)=>{
    console.log('Log recorded');
})
server.get('/reg',(req,res,next)=>{
    res.send('Registration successful');
    next();
});

server.get('/login',(req,res)=>{
    res.send('Login successful');
})

2. Built-in middleware

server.use(express.static('目录'))

Host static resource files in a certain directory. If the browser requests static resources, it will automatically search in this directory.

3. Third-party middleware

(1) body-parser, parses post request data into objects

const express = require('express');
//Introduce body-parser middleware const bodyParser=require('body-parser');

var server = express();
server.listen(3000);
// Host static resources to public
server.use(express.static('./public'));

//Use body-parser middleware to parse the post request data into an object //Extended Whether to use the extended qs module to parse into an object //If false, do not use it, and use the querystring module instead server.use(bodyParser.urlencoded(
    {extended:false}
))

server.post('/mylogin',(req,res)=>{
    console.log(req.body);
    res.send('Login successful');
})

(2) mysql module

Normal connection

//Introduce the mysql module const mysql =require('mysql');
//1. Normal connection //1.1 Create a connection var connection = mysql.createConnection({
    host:'127.0.0.1',
    port:'3306',
    user:'root',
    password:'1234',
    database:'tedu'
});
//1.2 Execute connection connection.connect();
//Execute SQL statement connection.query('select * from emp',(err,result)=>{
    if(err) throw err;
    console.log(result);
});
//Close the connectionconnection.end();

Connection Pool

const mysql = require('mysql');
//Use connection pool //Create connection pool object var pool = mysql.createPool(
    {
        host:'127.0.0.1',
        port:'3306',
        user:'root',
        password:'1234',
        database:'tedu',
        connectionLimit:20
    }
);
//Execute SQL statement pool.query('select * from emp where eid=2',(err,result)=>{
    if(err) throw err;
    console.log(result);
})
const mysql = require('mysql');
var pool = mysql.createPool({
    'host':'127.0.0.1',
    port:'3306',
    user:'root',
    password:'1234',
    database:'tedu',
    connectionLimit:20
})
//Use placeholders to insert data // pool.query("insert into emp values(?,?,?,?,?,?)",[null,'yt','1','1995-12-24','9000','20'],(err,result)=>{
// if(err) throw err;
// console.log(result);
// });
//Use object to insert data//var emp={
// eid:null,
// ename:'html',
// sex:1,
// birthday:'1995-12-25',
//salary:10000,
//deptid:30
// }
// pool.query('insert into emp set ?',[emp],(err,result)=>{
// if(err) throw err;
// console.log(result);
// })
//Use the placeholder to delete the data numbered 10 pool.query('delete from emp where eid=?',[10],(err,result)=>{
    if(err) throw err;
    console.log(result);
    if(result.affectedRows>0){
        console.log('Deleted successfully');
    }
    else{
        console.log('deletion failed');
    }
})

The above is a brief discussion of the detailed types of node.js middleware. For more information about node.js middleware, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • How to implement mock-plugin middleware in node
  • A brief discussion on Node.js middleware mode
  • Detailed explanation of routing, middleware, ge request and post request parameters in node.js
  • Detailed explanation of using node.js middleware express-session
  • In-depth understanding of Express middleware in nodejs
  • Nodejs development - express routing and middleware
  • NodeJS learning notes: Connect middleware application example
  • NodeJS learning notes: Connect middleware module (I)
  • Nodejs implements blacklist middleware design

<<:  Example of using Nginx reverse proxy to go-fastdfs

>>:  Detailed explanation of Nginx http resource request limit (three methods)

Recommend

How to strike a balance between ease of use and security in the login interface

Whether you are a web designer or a UI designer, ...

Detailed explanation of Vue3 sandbox mechanism

Table of contents Preface Browser compiled versio...

Some properties in CSS are preceded by "*" or "_".

Some properties in CSS are preceded by "*&qu...

How to implement two-way binding function in vue.js with pure JS

Table of contents First, let's talk about the...

Example code of html formatting json

Without further ado, I will post the code for you...

Simply understand the writing and execution order of MySQL statements

There is a big difference between the writing ord...

MySQL uses the truncate command to quickly clear all tables in a database

1. Execute the select statement first to generate...

JavaScript BOM Explained

Table of contents 1. BOM Introduction 1. JavaScri...

Several ways to update batches in MySQL

Typically, we use the following SQL statement to ...

How to uninstall MySQL 8.0 version under Linux

1. Shut down MySQL [root@localhost /]# service my...

WeChat applet realizes simple tab switching effect

This article shares the specific code for WeChat ...

What to do if the online MySQL auto-increment ID is exhausted

Table of contents Table definition auto-increment...

How to use node scaffolding to build a server to implement token verification

content Use scaffolding to quickly build a node p...

Detailed explanation of XML syntax

1. Documentation Rules 1. Case sensitive. 2. The a...

Each time Docker starts a container, the IP and hosts specified operations

Preface Every time you use Docker to start a Hado...