Express中间件

什么是中间件

中间件(Middleware) 本质是一个回调函数。

中间件函数 可以像路由回调一样访问 请求对象、响应对象。

中间件的作用

中间件的作用就是使用函数封装公共操作,简化代码。

中间件的类型

全局中间件

定义全局中间件

每一个请求 到达服务端之后 都会执行全局中间件函数。

声明中间件函数

javascript 复制代码
let recordMiddleware = function (request, response, next) {
  //实现功能代码
  //.....
  //执行next函数(当如果希望执行完中间件函数之后,仍然继续执行路由中的回调函数,必须调用next)
  next();
}

应用级中间件

javascript 复制代码
app.use(recordMiddleware);

声明时可以直接将匿名函数传递给 use

javascript 复制代码
app.use(function (request, response, next) {
  console.log('定义第一个中间件');
  next();
})
多个全局中间件

Express允许使用app.use() 定义多个全局中间件

javascript 复制代码
app.use(function (request, response, next) {
  console.log('定义第一个中间件');
  next();
})
app.use(function (request, response, next) {
  console.log('定义第二个中间件');
  next();
})

路由中间件

定义路由中间件

如果只需要对某一些路由进行功能封装,则就需要路由中间件

调用格式如下:

javascript 复制代码
app.get('/路径', `中间件函数`, (request, response) => {
});
app.get('/路径', `中间件函数1`, `中间件函数2`, (request, response) => {
});

静态资源中间件

Express内置处理静态资源的中间件

javascript 复制代码
//引入express框架
const express = require('express');
//创建服务对象
const app = express();
//静态资源中间件的设置,将当前文件夹下的public目录作为网站的根目录
app.use(express.static('./public')); //当然这个目录中都是一些静态资源
//如果访问的内容经常变化,还是需要设置路由
//但是,在这里有一个问题,如果public目录下有index.html文件,单独也有index.html的路由,
//则谁书写在前,优先执行谁
app.get('/index.html', (request, response) => {
  respsonse.send('首页');
});
//监听端口
app.listen(3000, () => {
  console.log('3000 端口启动....');
});

注意事项:

  1. index.html 文件为默认打开的资源
  2. 如果静态资源与路由规则同时匹配,谁先匹配谁就响应
  3. 路由响应动态资源,静态资源中间件响应静态资源

获取请求体数据body-parser

Express可以使用 body-parser 包处理请求体

第一步:安装

javascript 复制代码
npm i body-parser

第二步:导入body-parser包

javascript 复制代码
const bodyParser = require('body-parser');

第三步:获取中间件函数

javascript 复制代码
//处理 querystring 格式的请求体
let urlParser = bodyParser.urlencoded({extended:false}));
//处理 JSON 格式的请求体
let jsonParser = bodyParser.json();

第四步:设置路由中间件,然后使用request.body来获取请求体数据

javascript 复制代码
app.post('/login', urlParser, (request, response) => {
  //获取请求体数据
  //console.log(request.body);
  //用户名
  console.log(request.body.username);
  //密码
  console.log(request.body.userpass);
  response.send('获取请求体数据');
});

获取到的请求体数据为

javascript 复制代码
[Object: null prototype] { username: 'admin', userpass: '123456' }
相关推荐
RoyLin8 小时前
TypeScript设计模式:迭代器模式
javascript·后端·node.js
前端双越老师12 小时前
2025 年还有前端不会 Nodejs ?
node.js·agent·全栈
weixin_4569042713 小时前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
人工智能训练师21 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny0721 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
huangql5201 天前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
荣达1 天前
koa洋葱模型理解
前端·后端·node.js
csdn_aspnet1 天前
Windows Node.js 安装及环境配置详细教程
windows·node.js
风若飞2 天前
npm ERR! code CERT_HAS_EXPIRED
前端·npm·node.js
csdn_aspnet2 天前
Windows、Linux 系统 nodejs 和 npm 版本更新及错误修复
linux·windows·npm·node.js