You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express项目全局前置校验query字符串并自动补全参数的实现方法问询

实现方案

核心思路

利用Express的中间件机制,在路由挂载前注入校验补全逻辑,所有请求进入业务路由前会自动执行该逻辑,无需修改现有路由代码。

具体实现步骤

  • 把以下自定义中间件代码插入到app.js中静态资源中间件之后、路由挂载之前的位置,也就是app.use(express.static(path.join(__dirname, 'public'))); 之后,app.use('/', aRouter);之前即可:
// 全局query参数校验补全中间件
app.use(function(req, res, next) {
  // 1. 获取当前系统日期的年、月
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() + 1 // getMonth返回0-11,需+1转成1-12的自然月

  // 2. 参数补全+类型转换:如果参数不存在/值非法,自动补全为当前年月
  let reqYear = Number(req.query.year)
  let reqMonth = Number(req.query.month)
  if (isNaN(reqYear)) reqYear = currentYear
  if (isNaN(reqMonth)) reqMonth = currentMonth

  // 3. 合法性校验
  // 校验年份不能超过当前年份
  if (reqYear > currentYear) {
    return res.status(400).send({code: 400, msg: 'year参数非法,不能大于当前年份'})
  }
  // 校验月份范围1-12
  if (reqMonth < 1 || reqMonth > 12) {
    return res.status(400).send({code: 400, msg: 'month参数非法,需在1-12范围内'})
  }
  // 年份等于当前年份时,校验月份不能超过当前月份
  if (reqYear === currentYear && reqMonth > currentMonth) {
    return res.status(400).send({code: 400, msg: '当前年份下month参数不能大于当前月份'})
  }

  // 4. 校验通过,把处理后的合法参数挂载到req.query,后续路由直接读取即可
  req.query.year = reqYear
  req.query.month = reqMonth
  next()
})

可选优化

如果后续只需要部分路由走校验逻辑,可以把中间件抽离成独立函数,单独挂载到对应路由即可:

// 抽离为独立中间件函数
const validateQuery = function(req, res, next) {
  // 上述校验逻辑保持不变
}
// 仅给需要的路由挂载校验逻辑
app.use('/', validateQuery, aRouter)
app.use('/b', validateQuery, bRouter)
app.use('/c', validateQuery, cRouter)

内容的提问来源于stack exchange,提问作者홍종우

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:39:00