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

如何为所有PUT/POST请求批量应用checkSubscription中间件?

解决方案

你可以通过两种方式批量给PUT/POST路由应用checkSubscription中间件,无需逐个路由配置:

方法一:直接在路由顶部添加条件判断中间件

利用Express的路由中间件机制,在所有路由定义前添加一个中间件,仅当请求方法为PUT或POST时,才调用checkSubscription:

import { Router } from 'express';
import checkSubscription from './path/to/checkSubscription';

const router = Router();

// 批量拦截PUT/POST请求,应用订阅验证中间件
router.use((req, res, next) => {
  if (req.method === 'PUT' || req.method === 'POST') {
    return checkSubscription(req, res, next);
  }
  // 非PUT/POST请求直接跳过验证
  next();
});

// 后续正常定义所有路由
router.get('/items', (req, res) => {
  // GET请求无需验证,直接处理
  res.json({ data: [] });
});

router.post('/items', (req, res) => {
  // POST请求会自动经过checkSubscription验证
  res.status(201).json({ message: '创建成功' });
});

router.put('/items/:id', (req, res) => {
  // PUT请求会自动经过checkSubscription验证
  res.json({ message: '更新成功' });
});

router.delete('/items/:id', (req, res) => {
  // DELETE请求无需验证,直接处理
  res.json({ message: '删除成功' });
});

export default router;

方法二:封装辅助函数增强灵活性

如果以后需要调整需要验证的HTTP方法,或者在多个路由文件复用这个逻辑,可以封装一个辅助函数:

import { Router, RequestHandler } from 'express';
import checkSubscription from './path/to/checkSubscription';

const router = Router();

// 辅助函数:给指定HTTP方法批量应用中间件
const applyMiddlewareToMethods = (
  router: Router,
  targetMethods: string[],
  middleware: RequestHandler
) => {
  router.use((req, res, next) => {
    const upperCaseMethod = req.method.toUpperCase();
    if (targetMethods.includes(upperCaseMethod)) {
      return middleware(req, res, next);
    }
    next();
  });
};

// 调用辅助函数,指定只对PUT、POST应用订阅验证
applyMiddlewareToMethods(router, ['PUT', 'POST'], checkSubscription);

// 路由定义同上...

这两种方式都能在路由文件顶部批量配置,避免重复劳动,同时保证GET、DELETE请求不受订阅验证限制。

内容的提问来源于stack exchange,提问作者Saurav Ghimire

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:21:05