首页 > 解决方案 > 如何在路由器级别使用快速中间件

问题描述

我正在尝试为路由器级别的每个请求添加一个简单的中间件功能。

文档说明:

对路由器的每个请求都会执行一个没有挂载路径的中间件函数

在我的应用程序中,我只有一个带有一个端点的路由器,该端点正在侦听每个请求,并且我将中间件功能放置在此端点之上,但中间件永远不会启动。

快速设置:

const initializeExpress = (): void => {
  const port = process.env.PORT;
  const app = express();
  app.use(helmet());
  app.use(express.json());
  app.use(cors());
  app.use('/api', Router);

  app.listen(port, () => {
    console.log(`Listening for requests at http://localhost:${port}`);
  });
};

我的路由器代码:

const Router = express.Router();

Router.use((req, res, next) => {
  const token = req.header('authorization');
  if (!token) res.status(401).send({ message: 'Unauthorized' });

  const isAuthenticated = isAuthorized(token!);
  if (isAuthenticated) {
    next();
  } else {
    res.status(401).send({ message: 'Unauthorized' });
  }
});

Router.get(
  '/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?',
  async (req, res): Promise<void> => {
    const routeParams = filterRouteParams(req.params);
    const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
    if (await pathExists(path)) {
      const data = await getJsonFromPath(path);
      if (!isEmpty(data)) {
        res.status(200).json(data);
        return;
      }
      res.status(400).send({ message: 'Data not found' });
    }
  }
);

我在这里做错了什么?

标签: node.jsexpress

解决方案


中间件将在哪个路由上处于活动状态,您需要对其进行定义。

有两种方法可以做到这一点

首先,在您的路由之前调用中间件:

const Router = express.Router();

const myMiddleware = (req, res, next) => {
  const token = req.header('authorization');
  if (!token) res.status(401).send({ message: 'Unauthorized' });

  const isAuthenticated = isAuthorized(token!);
  if (isAuthenticated) {
    next();
  } else {
    res.status(401).send({ message: 'Unauthorized' });
  }
}

Router.get(
  '/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?',
myMiddleware(), //Call middleware here 
  async (req, res): Promise<void> => {
    const routeParams = filterRouteParams(req.params);
    const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
    if (await pathExists(path)) {
      const data = await getJsonFromPath(path);
      if (!isEmpty(data)) {
        res.status(200).json(data);
        return;
      }
      res.status(400).send({ message: 'Data not found' });
    }
  }
);

其次,为您定义的所有路由调用中间件:

const Router = express.Router();

const myMiddleware = (req, res, next) => {
  const token = req.header('authorization');
  if (!token) res.status(401).send({ message: 'Unauthorized' });

  const isAuthenticated = isAuthorized(token!);
  if (isAuthenticated) {
    next();
  } else {
    res.status(401).send({ message: 'Unauthorized' });
  }
}

Router.use('/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?', myMiddleware());

Router.get(
  '/:arg1/:arg1Id?/:arg2?/:arg2Id?/:arg3?/:arg3Id?/:arg4?/:arg4Id?'
  async (req, res): Promise<void> => {
    const routeParams = filterRouteParams(req.params);
    const path = basePath + getPathFromRouteParams(routeParams) + '/data.json';
    if (await pathExists(path)) {
      const data = await getJsonFromPath(path);
      if (!isEmpty(data)) {
        res.status(200).json(data);
        return;
      }
      res.status(400).send({ message: 'Data not found' });
    }
  }
);

推荐阅读