What is the Express framework

Express framework

  • What is Express

    Express is a web application development framework based on Node platform. It provides a series of powerful features to help you create various web applications.
    Create web server:

    const app=express()
    

    Create route:

    app.get("/list",(req,res)=>{
    	//send response browser
    	//1. The type of response content will be automatically detected
        //2. Automatically set the status code of http
        //3. Content types and codes that will help us respond automatically
        res.send("hello Express")
    })
    

    Listening port:

    app.listen(3000)
    
  • middleware

    1. What is middleware

      Middleware is a bunch of methods, which can receive the request from the client, respond to the request, or continue to hand over the request to the next middleware for further processing.

      Multiple middleware can be set for the same request to process the same request multiple times.

      By default, the request matches the middleware from top to bottom. Once the matching is successful, the matching is terminated.

      You can call the next method to hand over the control of the request to the next middleware until the middleware that ends the request is encountered.

      const express=require("express")
      //Create network server
      const app=express()
      app.get("/list",(req,res,next)=>{
          req.name="Zhang San"
      	next()
      })
      app.get("/list",(req,res,next)=>{
          res.send(req.name)
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
    2. app.use

      app.use matches all request methods. It can be directly passed into the request processing function to accept all requests

      const express=require("express")
      //Create network server
      const app=express()
      //Accept all requests
      //app.use matches all request methods. It can be directly passed into the request processing function to accept all requests
      app.use((req,res,next)=>{
          console.log("Please go app.use middleware ")
          next()
      })
      //When all customers access / list requests, go to the current middleware 
      //The first parameter of app.use can also pass in the request address, which means that no matter what the request method is, as long as it is the request address, it will receive the request.
      app.use("/list",(req,res,next)=>{
          console.log("Please go app.use/list middleware ")
      	next()
      })
      //Create a route to / admin. When the user accesses / localhost:3000/admin, the server will output "request left app.use middleware"
      //It does not output "request left app.use/list middleware". The second is a fixed request address, and the first accepts all requests
      app.get("/admin",(req,res,next)=>{
         console.log("hello admin")
      })
      //Create a route for / list
      app.get("/list",(req,res,next)=>{
          req.name="Zhang San"
      	next()
      })
      //Create a routing response of / list to the client
      app.get("/list",(req,res,next)=>{
          res.send(req.name)
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
    3. Middleware application

      Routing protection: when the client accesses the page to be logged in, it can first use the middleware to judge the user's login status. If the user does not log in, it will intercept the request and respond directly to prohibit the user from entering the page to be logged in.

      const express=require("express")
      //Create network server
      const app=express()
      //Website announcement
      //app.use((req,res,next)=>{
      //    res.send("website under maintenance...)
      //})
      app.use("dimin",(req,res,next)=>{
          //By default, the user is not logged in
          let isLogin=fales//False no login / true is login
          if(isLogin){
              //Request execution down
              next()
          }else{
              //If the user does not log in, respond directly to the client
              res.sen("The user has not logged in and cannot access/admin page")
          }
      })
      app.get("/admin",(req,res)=>{
          res.send("you are already logged in")
      })
      //When accessing a non / dimin route, the client responds to the status code 404
      app.use((req,res)=>{
          res.send("Access page does not exist")
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
    4. Error handling Middleware

      In the process of program execution, some unexpected errors will inevitably occur, such as file reading failure and database connection failure. Error handling middleware is a place where errors are handled centrally.

      const express=require("express")
      //Create network server 
      const app=express()
      const fs=require("fs")
      app.get("/index",(req,res)=>{
          // . / demo: create an error. Without this file, when reading an existing file, it will not handle the error handling middleware
          //When an error occurs in the program, call the next() method and pass the error information to the next() method in the form of parameters to trigger the error handling middleware.
          fs.readFile("./demo","utf8",(err,result)=>{
              if(err!=null){
                  next(err)
              }else{
                  res.send(result)
              }
          })
      })
      //Error handling Middleware
      app.use((err,req,res,next)=>{
          //Status sets the content of the status code response error
          res.status(500).send(err.message)
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
    5. Capture error

      In node.js, the error information of the asynchronous API is obtained through the callback function. Errors in the asynchronous API that supports Promise objects can be captured through the catch method. How to catch errors when asynchronous functions are executed?

      const express=require("express")
      //Create network server 
      const app=express()
      const fs=require("fs")
      const promisify=require("util").promisify
      const readFile=promisify(fs.readFile)
      app.get("/index", async (req,res,next)=>{
          //try catch can catch errors that occur during the execution of asynchronous functions and other synchronous code, but it cannot catch errors that occur in other types of API s.
          try{
              //It may run the wrong code, execute catch in case of error, and jump out of catch without error
              await readFile("./demo")
          }catch(ex){
              netx(ex)
          }
      })
      //Error handling Middleware
      app.use((err,req,res,next)=>{
          //Status sets the content of the status code response error
          res.status(500).send(err.message)
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
  • Building modular routing

    1. Basic code for building modular routing

      const express=require("express")
      //Create network server
      const app=express()
      //Create routing object
      const home=express.Router()
      //Match the route with the request path / first level routing
      app.use("/list",home)
      //Secondary route access: locahost:3000/list/index
      home.get("/index",(req,res)=>{
          res.send("Welcome to the home page")
      })
      app.listen(3000)
      console.log("Network server started successfully")
      
    2. Building modular routing

      //Route / home.js home.js under the route folder
      const express=require("express")
      //Create routing object (home routing object)
      const home=express.Router()
      home.get("/index",(req,res)=>{
          res.send("Welcome to the blog home page")
      })
      module.exports=home
      
      //Admin.js in the route / admin.js folder
      const express=require("express")
      //Create routing object (admin routing object)
      const admin=express.Router()
      //Secondary route access: locahost:3000/list/index
      admin.get("/index",(req,res)=>{
          res.send("Welcome to the blog management page")
      })
      module.exports=admin
      
      //app.js file
      const express=require("express")
      //Create network server
      const app=express()
      //Import home and admin modules
      const home=require("./route/home")
      const admin=require("./route/admin")
      //When the client accesses the / home route, use the home route. / / the same is true below
      app.use("/home",home)
      app.use("/damin",damin)
      app.listen(3000)
      console.log("Network server started successfully")
      
  • GET parameter acquisition

    The GET parameters can be obtained by using req.query in the Express framework. The GET parameters will be converted into objects and returned inside the framework.

    const express=require("express")
    //Create network server
    const app=express()
    app.get("/index",(req,res)=>{
        //Get get request parameters / / default {}
      	req.send(req.query)  
    })
    app.listen(3000)
    console.log("Network server started successfully")
    
  • POST request parameters

    Receiving post request parameters in Express requires the help of the third-party package body parser. (download the third-party module of body parser in advance)

    const express=require("express")
    const bodyParser=require("body-parser")
    //Create network server
    const app=express()
    //Block all requests
    //The extended:false method uses the querystring module internally to process the format of the request parameters
    //The extended:true method internally uses the third-party module qs to process the format of request parameters
    app.use(bodyParser.urlencoded({extended:false}))
    app.post("/add",(req,res)=>{
        //Accept parameters of post request
        res.send(req.body)
    })
    app.listen(3000)
    console.log("Network server started successfully") 
    
  • Express routing parameters

    const express=require("express")
    const bodyParser=require("body-parser")
    //Create network server
    const app=express()
    app.get("/index/:id/:name/:age",(req,res)=>{
        //Parameters to accept the request: parameters passed by the client locahost:3000/index /
        res.send(req.params)//{"id":123,"name":"zhangsan","age":10}
    })
    app.listen(3000)
    console.log("Network server started successfully") 
    
  • Processing of static resources

    With express.static built in Express, you can easily host static files, such as img, CSS, JavaScript files, etc.

    const express=require("express")
    const path=require("path")
    //Create network server
    const app=express()
    //Splicing the path of static resources under public
    const The_path = path.join(__dirname,"public")
    //Realize the static resource access function: loadhost: 3000 / the file you want to access
    //For example: localhost:3000/imges/bg.jpg
    app.use(express.static(The_path))
    app.listen(3000)
    console.log("Network server started successfully") 
    

Tags: node.js Front-end Middleware

Posted by chrispos on Wed, 10 Nov 2021 11:20:13 +0530