Node.Js (2)

express middleware

Express middleware is essentially a function processing function

const express = require('express')
const app = express();

app.get('/',function(req,res.next){
    
    
	next()
})

Note: The formal parameter list of the middleware function must contain the next parameter, while the route processing function only contains the req and res parameters

The next() function is the key to realize the continuous call of multiple middleware, and it means to transfer the flow relationship to the next middleware or route

Globally effective middleware:

Middleware defined with app.use()

Locally effective middleware:

Middleware defined by app.use() is not used

Define multiple partial middleware:

//The following two ways of writing are "completely equivalent", you can choose any way to use according to your own preferences app.get( '/' ,mw1,mw2, (req, res) => { res
. send("Home page.") app.get('/',[mw1,mw2],(req,res) =>
{ res.send('Home page."))

Notes on middleware:

1. Be sure to register the middleware before routing
2. The request sent by the client can call multiple middleware for processing continuously
3. After executing the business code of the middleware, don’t forget to call the next) function
4. In order to prevent code The logic is chaotic, don’t write extra code after calling next(function and call continuously 5. When multiple middlewares are used, the req and res objects are shared between multiple middlewares

Classification of middleware:

  • Routing-level middleware:
    Middleware bound to the express.Router() instance is called routing-level middleware

    var app = express()
    var router = app.Router()
    
    router.use(function(req,res,next){
          
          
    	console.log('Time',Date.new())
    	next()
    })
    
    app.use('/',router)
    
  • Application level middleware:

    The middleware bound to the app instance through app.use() or app.get() or app.post() is called application-level middleware

    //应用级别的中间件(全局中间件)
    app.use((req,res,next)=>{
          
          
    	next()
    })
    
    //应用级别的中间件(局部中间件)
    app.get('/',nm,(req,res)=>{
          
          
    	res.send('home page')
    })
    
  • error level middleware

    The role of error level middleware: it is specially used to catch abnormal errors that occur in the entire project, so as to prevent the problem of abnormal collapse of the project.
    **Format:** In the function processing function of the error level middleware, there must be 4 formal parameters, and the order of the formal parameters is (err, req, res, next).

    app.get( ' /", function (req,res) {
          
            //路由
    	throw new Error("服务器内部发生了错误!')//抛出一个自定义的误
    	res.send( "Home Page")
    })
    
     app.use(function (err, req,res,next){
          
          //错汉极励的中问件
         console.log( "发生了错误: ' +err.message)
    // 在服务器打印消息
    	res.send('Error! ' + err.message)//向客户靠家应错误相关的内容
     })
    
    

    Note: Put the error-level middleware after all routes

express built-in middleware

express.static Built-in middleware for fast hosting of static resources, such as: HTML

Files, images, CSS styles, etc. (no compatibility)

express.json parses the request body data in JSON format (with compatibility, only in

Available in version 4.16.0+)

express.urlencoded parses request body data in URL-encoded format (with

Compatibility, only available in version 4.16.0)

// Configure the built-in middleware for parsing data in application/json format app.use( express.json(o)
// Configure the built-in middleware for parsing application/x-www-form-urlencoded data
app.use(express. urlencoded({ extended: false }

third-party middleware

The middleware that is not officially built-in by Express but developed by a third party is called third-party middleware. In the project, you can download and configure third-party middleware on demand, so as to improve the development efficiency of the project.

Take the use of body-parser, a third-party middleware, as a demonstration step:

Run npm install body-parser to install middleware

Import middleware using require

Call app.use() to register and use middleware

custom middleware

Implementation steps:

  • Define middleware
  • Listen to the data event of req
  • Listen to the end event of req
  • Use the querystring module to parse request body data
  • Mount the parsed data object as req.body
  • Package custom middleware as a module
  1. Define middleware

    app.use(function(req.res,next) {
          
          
        //中间件的业务逻辑
    })
    
    
  2. Listen to the data event of req

    //定义变量。用来存储名户读发送过来的请求体数据
    let str = " "
    //监听req对象的 data 事件(客户读发试过来的新的清求体数购)
    req.on( ‘data' , (chunk)=>i
    //拼接请求体数据,转换为宁符串
    str += chunk
    
    
  3. Listen to the end event of req

    //监听req对象的end 事件(请求体发送完毕后自动触发)
    req.on( " end",()=>{
          
          
    	//打印完整的请求体数据
    	console.log(str)
    //TOD0:把字符串格式的请求体数据,解析成对象格式
    }
    
  4. Use the querystring module to parse request body data

    //导入处理querystring的 Node.js内置模块
    const qs = require( " querystring " )
    //调用qs.parse()方法,把查询字符串解析为对象
    const body = qs.parse(str)
    
    
  5. Mount the parsed data object as req.body

    req.on( " end' , ()> {
          
          
    	const body = qs.parse(str)  // 调用qs.parse()方法,把查询字符串解断为对象
    	req.body = body  //将解析出来的清求体对象。挂载为req.body属性
    	next()   //最后,一定要调用next()函数,执行后续的业务逻辑
    })
    
    
  6. Package custom middleware as a module

    write interface

    Write an interface using express

    1. Create a server

    const express = require('express')
    
    const app = express()
    
    app.listen(80,()=>{
          
          
    	conlose.log('http://127.0.0.1')
    })
    

    2. Create an API routing module

    // apiRouter.js【路由模块】
    const express - require( " express ')
    const apiRouter = express.Routero
    
    // bind your router here.. .
    
    
    module.exports = apiRouter
    
    // app.js 【导入并注册路由模块】
    const apiRouter = require( " ./apiRouter.js ")
    
    app.use( ' /api ' , apiRouter)
    
    

    To solve the cross-domain problem:

    There are two main solutions to solve the interface cross-domain problem:

    CORS (mainstream solution, recommended)
    JSONP (defective solution: only supports GET requests)

Use cors middleware to solve cross-domain problems:

cors 是Express的一个第三方中间件。通过安装和配置cors中间件,可以很方便地解决跨域问题。使用步骤分为如下3:
1.运行npm install cors安装中间件

2.使用const cors = require("cors')导入中间件

3在路由之前调用app.use(cors0)配置中间件

CORS cross domain resource sharing

  • CORS response header -Access-Control-Allow-Origin

An Access-Control-Allow-Origin field can be carried in the response header, and its syntax is as follows:
Access-Control-Allow-Origin: l*
Among them, the value of the origin parameter specifies the external domain URL that is allowed to access the resource. For example, the following field value will only allow requests from http://itcast.cn:
res.setHeader( ' Access-Control-Allow-Origin" , "http:llitcast.cn')

 如果指定了Access-Control-Allow-Origin字段的值为通配符*,表示允许来自任何域的请求,示例代码如下:
  res.setHeader( ' Access-Control-Allow-Origin" , "*")
  • Access-Control-Allow-Headers

By default, CORS only supports the client sending the following 9 request headers to the server:
Accept, Accept-Language, Content-Language, DPR, Downlink, Save-Data, Viewport-Width, Width, Content-Type (values ​​are limited to text/plain, multipart/form-data, application/x-www-form-urlencoded)
If the client sends additional request header information to the server, it needs to pass Access-Control-Allow- Headers
declare additional request headers. Otherwise, the request will fail this time!
//Allow the client to send additional Content-Type request headers and X-Custom-Header request headers to the server//Note; Use English numbers to divide multiple request headers 3 res.setHeader ('
Access-Control-Allow-Headers', 'Content-Type', 'X-Custom-Header')

  • Access-Control-Allow-Methods

By default, CORS only supports clients to initiate GET, POST, HEAD requests. If the client wants to request resources from the server through PUT, DELETE, etc., it needs to specify the HITP method
allowed by the actual request through Access-Control-Alow-Methods on the server side.
The sample code is as follows:
//Only allow POST, GET, DELETE, HEAD request methods res.setHeader( "Access-Control-Allow-Methods',"POST, GET, DELETE, HEAD') //Allow all HTTP request methods
res .setHeader( " Access-control-Allow-Methods " , "*')

cors request

  • simple request

A request that meets the following two conditions at the same time is a simple request:
Request method: one of GET, POST, HEAD
HTTP header information does not exceed the following fields: no custom header field, Accept, Accept-Language, Content-Language, DPR.Downlink, Save-Data, Viewport-Width, Width, Content-Type (only three values ​​application/x-www-form-
urlencoded, multipart/form-data, text/plain)

  • preflight request

As long as the request meets any of the following conditions, a preflight request is required:
the request method is other than GET, POST, HEAD, the request
method type request header contains a custom header field,
and the application/json format data is sent to the server
. Before the browser formally communicates with the server, the browser will first send an OPTION request for pre-check to know whether the server allows the actual request, so this OPTION request is called a "pre-check request". After the server successfully responds to the preflight request, the real request will be sent with real data.

The difference between a simple request and a preflight request:

The characteristics of simple requests: only one request will occur between the client and the server.
The characteristics of the preflight request: two requests will occur between the client and the server, and the real request will be initiated only after the OPTION preflight request is successful.

JSONP interface

Concept: browser-side via

Features: 1. JSONP is not a real Ajax request, because it does not use the XMLHttpRequest object.

2. JSONP only supports GET requests. Requests such as POST, PUT, DELETE are not supported.

Notes on creating the JSONP interface:
If CORS cross-domain resource sharing has been configured in the project, in order to prevent conflicts, the JSONP interface must be declared before configuring the CORS middleware. Otherwise, the JSONP interface will be processed as an interface with CORS enabled. The sample code is as follows:

//优先创建JsONP接口【[这个接口不会被处理成CORS接口】

 app.get( " /api/jsonp ' . (req, res) =>{
    
    })

//再配置CORS中问件【后续的所有接口,都会帔处理成CORS 接口】

 app.use(cors()


//这是一个开启了CORS 的接口
sapp.get( " /api/get". (req. res) =>{
    
     }

Steps to implement the JSONP interface:

1. Get the name of the callback function sent by the client

const functionName = req.query.callback

2. Get the data to be sent to the client in the form of JSONP

3. According to the data obtained in the first two steps, splice out a function call string

4. Respond to the client by splicing the string obtained in the previous step

Guess you like

Origin blog.csdn.net/m0_63679126/article/details/125473602