Nest: Cannot inject into middleware

Created on 23 Nov 2017  路  8Comments  路  Source: nestjs/nest

TypeError: Cannot set property 'oAuthServer' of undefined

@Component() export class OAuth2Server implements OnModuleInit

`@Middleware()
export class OAuth2Middleware implements NestMiddleware {

private logger: Logger = LoggerFactory.getLogger(this.constructor.name);


constructor(@Inject('OAuth2Server') private readonly oAuthServer: OAuth2Server) {
}

async resolve(...args: any[]): Promise<ExpressMiddleware> {
    return (req, res, next) => {
        next();
    };
}

}`

export class AuthModule implements NestModule { public configure(consumer: MiddlewaresConsumer) { consumer .apply(OAuth2Middleware) .forRoutes(..) } }

Most helpful comment

tsconfig.json "target": "es5" - cause the problem

All 8 comments

Hi @szkumorowski,
We need a little bit more context. This part looks fine.

Even so, there is problem with middlewares itself, actually any of examples in relation to middleware doesn't work except direct functions. Class resolve method is not executed.

` @ Middleware()
export class LoggerMiddleware implements NestMiddleware {

constructor() {
    console.log('constructor');
}

resolve(...args: any[]): ExpressMiddleware {
    console.log('resolve');
    return (req, res, next) => {
        console.log('Request...');
        next();
    };
}

}`

export class AuthModule implements NestModule { configure(consumer: MiddlewaresConsumer): void { consumer.apply(LoggerMiddleware).forRoutes( { path: '/**', method: RequestMethod.POST }, ); } }

Server is not responding.
Logs:
constructor

Nothing more.

I have tested 01-cats-app example right now, which has the same middleware. Everything is working fine, we still need more context

tsconfig.json "target": "es5" - cause the problem

I experienced this same issue, but was due to having multiple tsconfig files in my project -- front end uses es5 target and is named tsconfig.json so ts-node picked it up for my dev server. changing index.js to

require('ts-node').register({project: 'nestjs.tsconfig.json'});
require('./server');

with project being whatever your alternate tsconfig file's name.

This PR https://github.com/nestjs/docs.nestjs.com/pull/43 adds a warning that target: es6 is required.

As a new user I would expect a sentence in the Documentation / "First Steps" telling me what is needed in tsconfig.json like

{
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "target": "es6"
}

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

yanshuf0 picture yanshuf0  路  3Comments

cojack picture cojack  路  3Comments

menme95 picture menme95  路  3Comments

2233322 picture 2233322  路  3Comments

breitsmiley picture breitsmiley  路  3Comments