Express 中间件分类

Express 中间件分类

在Express中应用程序可以使用以下类型的中间件:

1. 应用程序级别中间件

  • 不做任何限定的中间件
	app.use((req, res, next) => {
	  console.log("不做任何限定的中间件");
	  //交出执行权,往后继续匹配执行
	  next();
	});
  • 限定请求路径的中间件
	app.use("/user/:id", (req, res, next) => {
	  console.log("限定请求路径的中间件", req.method);
	  next();
	});
  • 限定请求路径的中间件多函数
	app.use(
	  "/user/:id",
	  (req, res, next) => {
	    console.log("限定请求路径的中间件多函数1", req.method);
	    //这个next 会脱离当前处理栈,往后查找匹配调用
	    next();
	  },
	  (req, res, next) => {
	    console.log("限定请求路径的中间件多函数2", req.method);
	    next();
	  }
	);
	//next('route')跳过当前后续的中间件
	app.use(
	  "/user/:id",
	  (req, res, next) => {
	    console.log("next('route')跳过当前后续的中间件", req.params.id === "0");
	    //这个next 会脱离当前处理栈,往后查找匹配调用
	    if (req.params.id === "0") {
	      next('route')
	    } else {
	      next();
	    }
	  },
	  (req, res, next) => {
	    console.log("id不是0没跳过", req.method);
	    next();
	  }
	);
	//传数组的中间件
	function middlewareUrl(req, res, next) {
	  console.log("middlewareUrl", req.originalUrl);
	}
	function middlewareUrl(req, res, next) {
	  console.log("middlewareUrl", req.originalUrl);
	}
	app.get("/user/:id", [middlewareUrl, middlewareUrl], (req, res, next) => {
	  res.cookie("foo", "bar");
	  res.status(201).send({
	    name: "xzx",
	  });
	  next();
	});

2. 路由级别中间件

	//1.创建路由实例
	//路由实例其实就相当于一个mini Express实例
	const router = express.Router();

	//2.配置路由
	router.get("/foo", (req, res) => {
	  res.send("get /foo");
	});

	router.post("/foo", (req, res) => {
	  res.send("get /foo");
	});
	//3.导出路由实例
	module.exports = router
	//4.将路由集成到 Express 实例应用中
	//给路由限定访问前缀
	//app.use('/todos',router)

3. 错误处理中间件

  • 在所有的中间件之后挂载错误处理中间件
	app.use((err,req,res,next)=>{
	  console.log('错误',err);
	  res.status(500).json({
		error: err.message 
	  })
	})
  • 在接口中间件中使用
	router.get("/", async (req, res, next) => {
	  try {
		const list = await getDb();
		res.status(200).json(list.todos);
	  } catch (error) {
		//传除了'route'之外的任何东西,都会传到下一个中间件函数
		next(error)
	  }
	});
  • 通常会在所有的路由之后配置处理404的内容
  • 请求依次匹配最后没有匹配到会走到这个404
	app.use((req,res,next)=>{
	  res.status(404).send('404 Not Found.')
	})

4. 内置中间件

	//解析Content-Type为application/json格式的请求体
	express.json()
	//解析Content-Type为application/www-form-urlencoded格式
	express.urlencoded()
	//解析Content-Type为application/octet-stream格式的请求体
	express.raw()
	//解析Content-Type为test/plain格式的请求体
	express.test()
	//托管静态资源文件
	express.static()

5. 第三方中间件

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值