首页 文章

Node Koa如何将参数传递给中间件?

提问于
浏览
0

将我的Express应用程序转换为Koa ...

我正在谷歌搜索,我在谷歌上搜索,我找不到如何将额外的参数传递给Koa中间件 . 例如...

router.post('/', compose([
    Midware.verifyAuthToken, 
    Midware.bodySchemaTest(UserController.bodyAttribs),
    Midware.injectionTest
]), UserController.postNew);

我需要将一些变量bodyAttribs(字符串数组)名称发送到bodySchemaTest中间件,我不知道如何在Koa中执行此操作 .

我现在正在尝试Koa . 请分享您的专业知识:-)

1 回答

  • 0

    好的,我自己做了 . 不确定这是否是智能或"right"方式来做到这一点,但我的解决方案是在每个控制器中创建一个中间件,在 ctx.state .bodyAttribs中设置预期的模式属性 .

    像这样...

    // /src/routers/user.router.ts
    
    import * as UserController from '../controller/user.controller';
    import * as Midware from './middleware';
    import Router from 'koa-router';
    import compose from 'koa-compose';
    
    const router = new Router();
    router.prefix('/user');
    
    router.get('/', Midware.verifyAuthToken, UserController.getAll);
    
    router.post('/', compose([
        UserController.bodyAttribs,
        Midware.verifyAuthToken,
        Midware.bodySchemaTest,
        Midware.injectionTest,
    ]), UserController.postNew);
    
    module.exports = router;
    
    
    // /src/controller/user.controller.ts 
    
    import { Context } from 'koa';
    import { UserData } from '../data/mongo/user.data.mongo';
    import { UserModel } from '../model/user.model';
    import { EmailValidate } from '../service/email-validate.service';
    import * as Logger from '../util/logger';
    
    const dataContext = new UserData();
    
    // Middleware to set bodyAttribs
    export const bodyAttribs = async (ctx: Context, next: any) => {
        ctx.state.bodyAttribs = ['handle', 'processUserOptions', 'name', 'email', 'pass', 'passConfirm'];
        return await next();
    };
    ...
    

    因此,每个控制器都提供自定义中间件,用于设置我想要验证的自定义bodyAttribs . 你可以使用这种方法在ctx.state中设置并传递1到任意数量的额外参数,无论你需要什么,它总是继续到链中的下一个中间件 . 跟随? :-)

相关问题