Express learning (1)

For other modules in node.js, I will slowly sort out the following and then record. These two days, I can hardly hold anything in my head. Let’s record the study of express first today.

1. Installation and simple use

​ First create a new folder:

​ Execute npm init to initialize, which is convenient to record the packages we installed

Execute npm iinstall express, wait for a while and then create a new index.js to try to build the server. The code is as follows:

/*
 * @Author:梅子黄时雨
 * @Date: 2023-02-10 10:25:34
 * @LastEditTime: 2023-02-10 11:40:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nodeTest\node\express学习\index.js
 */
//导入,挂载
const express = require('express')
const app = express()

// 第一个参数是路径,支持字符串,字符串模式以及正则模式进行匹配
//第二个参数是个回调函数,具体的放到后续来写~
app.get("/", (req, res) => {
    
    
  //req指的是前端的请求参数,res指的是我们要返回给前端的响应参数
  // send()方法封装了之前的res.write()和res.end(),支持字符串/html模板/json并返回给前端
  // res.send(`
  //   <html>
  //     <h1>Hello world</h1>
  //   </html>
  // `)
  res.send({
    
    
    name: 'libai'
  })
})
//支持的路径模式如下:
//表示匹配/abd或者/abcd的路径
app.get("/ab?cd", (req, res) => {
    
    
  res.send("login")
})
// 表示符合/ab/内容格式的路径
app.get("/ab/:id", (req, res) => {
    
    
  res.send("login")
})
// 表示复合在ab和cd之间添加n个字符串的字符
app.get("/ab*cd", (req, res) => {
    
    
  res.send("login")
})
// 表示当前字符重复n次的路由
app.get("/ab+cd", (req, res) => {
    
    
  res.send("login")
})
// 表示当前字可选的路由 cd可都写也可都不写
app.get("/ab(cd)?ef", (req, res) => {
    
    
  res.send("login")
})
// 正则表达式匹配
app.get("/.*fly$/", (req, res) => {
    
    
  res.send("fly")
})

app.listen(10086, () => {
    
    
  console.log("server start")
})

Now start the server, enter the above path to access the corresponding page (feeling: the path of express is really flexible)

2. Middleware

​ We refer to the callback functions mentioned above as middleware. Middleware actually refers to a function that can access the request object, the response object, and the middleware in the request-response loop process in the web application, generally named next variable. If the current middleware does not end the request-response loop, the next method must be called to pass control to the next middleware, otherwise the request will hang. It functions as follows:

  • execute any code

  • Modification request and corresponding object

  • Ending the request-response loop

  • The next middleware in the call stack

    ​ Write a simple example to understand the middleware: As a backend person, when operating on the frontend and passing parameters to the backend, the processing at this time is generally divided into three steps:

    1. Get the parameters given by the front end to verify whether its token has expired,
    2. to query the database
    3. Read data for processing and return to the front end.

    Assuming that the front-end needs a lot of data, you need to look up several tables, and then go through a series of complicated processing to stitch them together. On the one hand, if all the codes are written in one function at this time, the function body will be very bloated. On the other hand, On the one hand, this process is a step-by-step process, first do the first step, and then proceed to the second and third steps. At this time, the role of middleware is reflected: first verify whether the token is passed, if not, directly res.send('error'), if passed, then next() releases to execute the next middleware until there is res.send () returns data and response to the front end. And the three steps can be encapsulated into three functions, and the usage is very flexible. Please see the figure below:

/*
 * @Author:梅子黄时雨
 * @Date: 2023-02-10 10:25:34
 * @LastEditTime: 2023-02-10 13:54:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nodeTest\node\express学习\index.js
 */
const express = require('express')
const app = express()

const func1 = (req, res, next) => {
    
    
  // 验证token  
  // 查询数据库
  // 返回内容  
  console.log('验证token')
  // 在函数中要不然用send退出,要不然用next放行
  // 中间件互相通信,在next之前,利用res加属性挂值
  res.name = "李白"
  next()
}
const func2 = (req, res, next) => {
    
    
  res.send({
    
    
    list: [1, 2, 3, 4, 5],
    name: res.name
  })
}
app.get('/home',[func1,func2]) 
app.get("/list", [func1],(req, res) => {
    
    
  res.send({
    
    
    name: "hanxin"
  })
})
app.listen(10086, () => {
    
    
  console.log("server start")
})

The role of middleware is reflected, and he can configure it by himself. This shows that the number is customized by us, that is, the middleware can be configured according to the requirements and the principle of reducing code coupling.

In express, middleware is roughly divided into the following types:

  • application-level middleware

  • Router-level middleware

  • error handling middleware

  • built-in middleware

  • third party middleware

Let’s write application-level middleware and routing middleware first.

application-level middleware

​ Application-level middleware: similar to Vue's navigation guard, usage: app.use (fcuntion), but pay attention to the location of use, once hung on the app, all applications will use it, if you write an interception error Yes, it is mounted before all the middleware, and what you will always see is the page that handles errors~~ Not much to say, here is the code:

/*
 * @Author:梅子黄时雨
 * @Date: 2023-02-10 10:25:34
 * @LastEditTime: 2023-02-10 13:54:28
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nodeTest\node\express学习\index.js
 */
const express = require('express')
const app = express()

app.get("/", (req, res) => {
    
    
  res.send({
    
    
    name: 'libai'
  })
})
// 默认路径/放在use方法之前,所以不会去执行以下定义的中间件

// next():执行完当前函数继续执行下一个函数
const func1 = (req, res, next) => {
    
    
  //验证token,cookie是否过期
  // 查询数据库
  // 返回内容
  console.log('验证tooken')
  // 中间件互相通信,在next之前,利用res加属性挂值
  res.name = "李白"
  next()
}
app.use(func1) //挂载func1,以下出现的路径都首先要去执行func1
const func2 = (req, res, next) => {
    
    
  res.send({
    
    
    list: [1, 2, 3, 4, 5],
    name: res.name
  })
}
app.get("/home", [func2])
app.get("/list", (req, res) => {
    
    
  res.send({
    
    
    name: "hanxin"
  })
})
app.listen(10086, () => {
    
    
  console.log("server start")
})

Restart the server, and you will find that there will be no verification token in the console except for the path http://localhost:10086, and func1 will be executed in the path behind the access

It is convenient when it is convenient, but you must pay attention to the location of the mount.

Router-level middleware

Routing-level middleware is naturally used to process routing. Compared with the trouble of configuring a route in the previous section, the routing middleware provided by express and the method of obtaining parameters are really simple. Let’s take a look at the specific usage. Let’s divide all the routes according to the directory to create corresponding folders and set the entry index file:

/*
 * @Author:梅子黄时雨
 * @Date: 2023-02-10 13:57:07
 * @LastEditTime: 2023-02-10 17:29:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nodeTest\node\express学习\路由中间件.js
 */
//入口文件
const express = require('express')
const app = express()
const HomeRouter = require('./homerouter.js')
const LoginRouter = require('./loginRouter')

function application(req, res, next) {
    
    
  console.log("应用中间件,验证tooken")
  next()
}
app.use(application)
// 应用级别,有顺序的
// 配置post参数的中间件
app.use(express.urlencoded({
    
     extended: false }))//解析前端参数格式
app.use(express.json()) //解析前端参数格式
app.use("/home", HomeRouter)//控制一级匹配 匹配到/home目录下的路由
app.use("/login", LoginRouter)//控制一级匹配 匹配到/login目录下的路由
app.use((req, res) => {
    
    
  res.status(404).send('丢了')//调用send,返回的状态码一定是200,用status可以返回其他的
})//控制一级匹配 匹配到ogin目录下的路由
app.listen(10086, () => {
    
    
  console.log("server start")
})

Create a new HomeRouter, LoginRouter to store the functions corresponding to their respective functions, and import them into the entry file for matching. Let's focus on how to obtain the parameters passed by the front end, and use a small tool postaman. Let's record the use of login to achieve parameter passing and acquisition function of the parameter

/*
 * @Author: 梅子黄时雨
 * @Date: 2023-02-10 13:57:07
 * @LastEditTime: 2023-02-10 17:33:45
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \nodeTest\node\express学习\路由中间件.js
 */
const express = require('express')
const router = express.Router()
// 路由级别中间件,响应前端的get请求
 router.get('/', (req, res) => {
    
    
  console.log(req.query) //获取get请求参数
   res.send('login-success')
 })
// 路由级别中间件,响应前端的post请求
router.post('/', (req, res) => {
    
    
  console.log('req>>', req) //获取post请求参数,必须配置中间件  
  res.send({
    
     ok: 4 })
})
module.exports = router

Restart the server, let's test the result:
insert image description here
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weixin_44813858/article/details/128978068