中间件Middleware
含义:中间件就是在处理一个请求过程中执行的函数,这个函数自动调用,可以接受到一些传入的参数。
中间件语法:
// 定义中间件 /* @req 请求相关数据 @res 响应相关数据 @next 放行 否则请求会停止,一直转圈圈 */ function mw(req,res,next) { console.log('中间件') } // 全局使用 app.use(mw)
全局中间件
- 每一个请求都会生效的中间件
- app.use(中间件名称)
- 可以使用 app.use() 连续定义多个全局中间件。客户端请求到达服务器之后,会按照中间件定义的先后顺序依次进行调用
const express = require('express'); const app = express(); function mw(req,res,next){ console.log('中间件01') next() } function mw1(req,res,next){ console.log('中间件02') next() } function mw2(req,res,next){ console.log('中间件03') next() } app.use(mw) app.use(mw1) app.use(mw2) app.get('/', function (req, res) { res.send('Hello World!'); }); app.get('/list', function (req, res) { res.send('Hello World!'); }); const server = app.listen(3000, function () { console.log('Example app listening at http://localhost:3000'); });
局部中间件
- 只针对与某个请求生效的中间件
function mw3(req,res,next){ console.log('中间件04') next() } function mw4(req,res,next){ console.log('中间件05') next() } function mw5(req,res,next){ console.log('中间件06') next() } app.get('/goods',mw3, function (req, res) { res.send('goods!'); }); app.get('/list',[mw4,mw5], function (req, res) { res.send('list!'); });
中间件模型
- 洋葱模型
- 代码
function mw(req,res,next){ console.log('中间件01前') next() console.log('中间件01后') } function mw1(req,res,next){ console.log('中间件02前') next() console.log('中间件02后') } function mw2(req,res,next){ console.log('中间件03前') next() console.log('中间件03后') }
中间件注意事项
- 一定要在路由之前注册中间件
- 客户端发送过来的请求,可以连续调用多个中间件进行处理
- 执行完中间件的业务代码之后,不要忘记调用 next() 函数
- 为了防止代码逻辑混乱,调用 next() 函数后不要再写额外的代码
内置中间件
- express.static 快速托管静态资源的内置中间件,例如: HTML 文件、图片、CSS 样式等
app.use(express.static(__dirname + '/public')) // or app.use(express.static(path.join(__dirname, 'public')));//和上面是一样的
- 此时在浏览器地址栏输入
http://localhost:端口号/文件路径
就可以访问了,注意访问的时候不需要加pulic路径
第三方中间件
- 之前我们讲过可以利用node配置代理,在node中配置代理需要用到
http-proxy-middleware
,这个中间件express没有内置使用的时候需要下载 - 使用步骤
- 安装
npm install http-proxy-middleware --save
- 在app.js配置
const { createProxyMiddleware } = require('http-proxy-middleware'); const options = { target: 'http://localhost:8888/', // 目标源 changeOrigin: true, pathRewrite: { '^/api': '' // 去除路径中的/api } }; // 所有本地请求中带有/api路径的都会被指向http://localhost:8888 app.use('/api', createProxyMiddleware(options))
const xhr = new XMLHttpRequest xhr.open('get', '/api/test/first',false) xhr.send() console.log(xhr.responseText) xhr.open('get', '/api/test/first',false) xhr.send() console.log(xhr.responseText)
- 安装
- 之前我们讲过可以利用node配置代理,在node中配置代理需要用到