当前位置: 首页 > news >正文

Express中间件

1.创建最基本的中间件

const express = require('express');
const send = require('send');const app = express()const mw = function (req, res, next) {console.log('middleware');// 一定要调用next()  把流转关系交给下一个中间件或路由next()
}app.listen(80, () => {console.log('express server running at ');})

2.全局生效的中间件

客户端发起的任何请求,到达服务器之后,都会触发的中间件

const express = require('express');
const send = require('send');const app = express()const mw = (req, res, next) => {console.log('middleware');// 一定要调用next()  把流转关系交给下一个中间件或路由next()
}// 将mw注册为全局生效的中间件
app.use(mw)app.get('/', (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})

3.局部生效的中间件

const express = require('express');
const send = require('send');const app = express()const mw1 = (req, res, next) => {console.log('mw1');next()
}// 局部生效
app.get('/', mw1, (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})

多个局部生效的中间件

const express = require('express');
const send = require('send');const app = express()const mw1 = (req, res, next) => {console.log('mw1');next()
}
const mw2 = (req, res, next) => {console.log('mw2');next()
}
// 局部生效
// app.get('/', [mw1,mw2], (req, res) => {  也行
app.get('/', mw1,mw2, (req, res) => {res.send('Home Page')
})app.get('/user', (req, res) => {res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})

4.中间件的作用

 

 5.中间件注意事项

中间件必须在路由之前注册

 

6.中间件分类

  • 应用中间件
  • 路由中间件
  • 错误级别中间件

             错误级别中间件必须在所有路由之后

  • 内置中间件

举例:express.json()

const express = require('express');
const send = require('send');
const app = express()// 配置解析表单数据的中间件
app.use(express.json())app.get('/', (req, res) => {console.log(req.header, req.body);res.send('User Page')
})
app.listen(80, () => {console.log('express server running at ');})

7.自定义中间件

08.中间件-自定义中间件_哔哩哔哩_bilibili

http://www.lryc.cn/news/117618.html

相关文章:

  • 124. 二叉树中的最大路径和
  • 管理类联考——逻辑——论证逻辑——汇总篇——真题和典例——分析
  • 深度ip转换器:一键更换ip地址方法
  • 【TypeScript】类型断言-类型的声明和转换(五)
  • 行业追踪,2023-08-10
  • Nodejs下动态加载文件夹下的文件模块
  • C#实现旋转图片验证码
  • MySQL—缓存
  • IP提取器对比器
  • 【Spring Boot】构建RESTful服务 — RESTful简介
  • 模仿火星科技 基于cesium+水平面积测量+可编辑
  • 26.配电网规划——考虑潮流约束的配电网规划
  • 【云原生】K8S集群
  • python接口自动化之自动发送测试报告邮件
  • umi出现“Cannot find module ‘umi-build-dev/lib/routes‘“ 错误
  • Redis类型检查与命令多态
  • mysql支持的xa具体指的是什么?
  • IntelliJ Idea 编译时控制台上中文输出乱码
  • 锚框【目标检测】
  • 001-Spring boot 启动内置Web容器分析
  • 【Cocos Creator 项目实战 】消灭星星加强版(附带完整源码工程)
  • 2023软件测试岗必问的100个面试题【含答案】
  • MediaExtractor MediaCodec手动解码播放音乐
  • element表格+表单+表单验证结合运用
  • 亚马逊云科技发布Amazon HealthScribe,使用生成式AI技术实现临床文档的自动生成
  • Windows11安装Linux子系统,并实现服务自启动,局域网访问,磁盘挂载
  • 【Git】保姆级详解:Git配置SSH Key(密钥和公钥)到github
  • 离线环境conda虚拟环境备份迁移--conda pack问题
  • 挂载 IK 分词器至 Elasticsearch Docker 容器 - Docker Docker Compose 教程
  • 7.6 通俗易懂解读残差网络ResNet 手撕ResNet