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 use the dig/nslookup command to view DNS resolution steps

dig - DNS lookup utility When a domain name acces...

Ubuntu 18.04 disable/enable touchpad via command

In Ubuntu, you often encounter the situation wher...

How to use indexes to optimize MySQL ORDER BY statements

Create table & create index create table tbl1...

IIS7~IIS8.5 delete or modify the server protocol header Server

Requirements: Remove HTTP response headers in IIS...

How to add conditional expressions to aggregate functions in MySql

MySQL filtering timing of where conditions and ha...

v-for directive in vue completes list rendering

Table of contents 1. List traversal 2. The role o...

Install .NET 6.0 in CentOS system using cloud server

.NET SDK Download Link https://dotnet.microsoft.c...

Query process and optimization method of (JOIN/ORDER BY) statement in MySQL

The EXPLAIN statement is introduced in MySQL quer...

Steps to deploy multiple tomcat services using DockerFile on Docker container

1. [admin@JD ~]$ cd opt #Enter opt in the root di...

Three.js sample code for implementing dewdrop animation effect

Preface Hello everyone, this is the CSS wizard - ...

CSS code to achieve background gradient and automatic full screen

CSS issues about background gradient and automati...

Docker learning method steps to build ActiveMQ message service

Preface ActiveMQ is the most popular and powerful...