Web development Nodejs framework Express middleware usage

Preface

Learning web development has been a bit messy recently. I have understood all parts of web development. I have a certain idea about web development. Now I will summarize the usage of middleware in the Express framework of Nodejs in the past two days.
Middleware is a bunch of methods that can accept requests from clients, respond to requests, or pass the requests to the next middleware for processing. Specifically used to accept requests for processing requests.
The middleware can separate complex requests, and can also do some verification on the requests.
Past review of web development column:


Regarding the download of the Express framework, you can download it directly using npm. For more information about the Express framework, please check the official Express documentation .


What is middleware?

The middleware consists of two parts, the middleware method and the request processing function.
The middleware method is provided by the Express framework and is responsible for intercepting the request, and the request processing function is provided by the developer and is responsible for processing the request.
The following is a sample program:

app.get('请求路径',处理函数)
app.post('请求路径',‘处理函数’)

The Express framework can set up middleware for the same request and process the same request multiple times.
By default, the request matches the middleware from top to bottom. Once the matching succeeds, the matching is terminated, which causes the request to fail to match the middleware below. The Express framework provides the next method. The next method is called to transfer the control of the request to the next middleware, and the middleware that ends the request has been encountered.
The following is the sample code:

const express =require('express');
//创建网站服务器
const app=express();
app.get('/request',(req,res,next)=>{
    
    
    req.name='张三';
    next();
})
app.get('/request',(req,res)=>{
    
    
    res.send(req.name);
})
//监听端口
app.listen(8000);
console.log("网站服务器启动成功!")

app.use middleware usage

1. app.use middleware can directly match all request methods, and can directly pass in the request processing function, which means that all requests are accepted.
Sample program

app.use((req,res,next)=>{
    
    
  console.log('请求了app.use中间件')
  next();
});

2. The first parameter of app.use middleware can also be passed into the request address, which means that no matter what the request method is, the request will be received as long as it is the request address.

app.use('/request',(req,res,next)=>{
    
    
  console.log('请求了app.use中间件/request')
   next();
 });

Middleware application

1. Route protection. When the
client accesses the page that needs to be logged in, it can first use the middleware to determine the user's login status. If the user is not logged in, the request will be intercepted and the request will be responded directly to prohibit the user from entering the page that needs to be logged in.

const express =require('express');
//创建网站服务器
const app=express();
app.use('/admin',(req,res,next)=>{
    
    
  let isLogin=false;
  if(isLogin){
    
    
    next();
  }else{
    
    
   res.send('您还没有登陆,请先登陆!');
  }
});

app.get('/admin',(req,res)=>{
    
    

  res.send('您已经登陆,可以访问当前页面!')
});
//监听端口
app.listen(800);
console.log("网站服务器启动成功!")

2. Website maintenance announcement
Define the middleware that receives all requests at the top of all routes, and directly respond to the client.

const express =require('express');
//创建网站服务器
const app=express();
app.use((req,res,next)=>{
    
    
    res.send('当前网络正在维护.....')
});
app.use('/admin',(req,res,next)=>{
    
    
    let isLogin=false;
    if(isLogin){
    
    
        next();
    }else{
    
    
        res.send('您还没有登陆,请先登陆!');
    }
});
app.get('/admin',(req,res)=>{
    
    
    res.send('您已经登陆,可以访问当前页面!')
});
//监听端口
app.listen(800);
console.log("网站服务器启动成功!")

3. Custom 404 page
When the page visited by the user does not exist, the 404 page appears.

Note: The status code of page u that does not exist is 404, and the status code given by the express framework is 200. If you need to change it, you can use res.status(404) to modify the status code.

const express =require('express');
//创建网站服务器
const app=express();
//创建错误
app.get('/index',(req,res)=>{
    
    
   throw new Error('程序发生了未知错误!')
})
//错误处理中间件
app.use((err,req,res,next)=>{
    
    
 res.status(500).send(err.message);
})
//监听端口
app.listen(800);
console.log("网站服务器启动成功!")

Catch error

In nodejs, the error information of the asynchronous API is obtained through the callback function, and the asynchronous API that supports the Promise object can be caught by the catch method. If an error occurs in asynchronous function execution, how to catch the error?

Try catch can catch errors that occur during the execution of asynchronous functions and other synchronous codes, but it cannot catch errors that occur with other types of API.
The sample code is as follows:

const express =require('express');
const fs=require('fs');
//默认情况下fs是不支持异步的,需要对读取文件进行改造
const  promisify=require('util').promisify;
const readFile=promisify(fs.readFile);
//创建网站服务器
const app=express();
app.get('/index',async (req,res,next)=>{
    
    
    try{
    
    
        await readFile('./aaa.js')
    }catch(ex){
    
    
   next(ex);//触发错误处理中间件
    }
})
//错误处理中间件
app.use((err,req,res,next)=>{
    
    
 res.status(500).send(err.message);
})
//监听端口
app.listen(800);
console.log("网站服务器启动成功!")

Note: In the try-catch method, if an error occurs in the try method, execute the catch statement, use next (ex) to trigger the error handling middleware, and hand the request to the next middleware (error handling middleware) to respond to the error message .

Guess you like

Origin blog.csdn.net/JIANGYINGH/article/details/107005886