这种情况在express下怎么添加中间件?

express里一般这样添加中间件
image.png
但我的把路由并到一起了,用了一个循环来读取

AppRoutes.forEach(route => {
        app[route.method](route.path, (request: Request, response: Response, next: Function) => {
            route.action(request, response)
                .then(() => next)
                .catch(err => next(err));
        });
    });

路由文件 :

import {postGetAllAction} from "./controller/PostGetAllAction";
import {postGetByIdAction} from "./controller/PostGetByIdAction";
import {postSaveAction} from "./controller/PostSaveAction";
import {getAdmin} from './controller/GetAdmin'
/**
 * All application routes.
 */
export const AppRoutes = [
    {
        path: "/admin",
        method: "get",
        action: getAdmin
    },
    {
        path: "/posts",
        method: "get",
        action: postGetAllAction
    },
    {
        path: "/posts/:id",
        method: "get",
        action: postGetByIdAction
    },
    {
        path: "/posts",
        method: "post",
        action: postSaveAction
    }
];

这种情况下我怎么在循环里添加中间件?

阅读 1.5k
1 个回答

// 多个handler 可以直接使用数组(配置中action换成数组类型),express是支持的

AppRoutes.forEach(route => {

    app[route.method](route.path, route.action);
});

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进