I try to follow the documentation of nestjs middleware and I have a problem on my nest application after adding and set a middleware. I've seen the FAQ about the same common error from nestjs itself but still confused to solve this problem.
Error on my terminal
Error: Nest can't resolve dependencies of the AppModule (?). Please make sure that the argument Object at index [0] is available in the AppModule context.
Potential solutions:
- If Object is a provider, is it part of the current AppModule?
- If Object is exported from a separate @Module, is that module imported within AppModule?
@Module({
imports: [ /* the Module containing Object */ ]
})
at Injector.lookupComponentInParentModules (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:230:19)
at Injector.resolveComponentInstance (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:184:33)
at resolveParam (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:106:38)
at async Promise.all (index 0)
at Injector.resolveConstructorParams (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:121:27)
at Injector.loadInstance (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:52:9)
at Injector.loadProvider (c:\codelab\nestlab\node_modules\@nestjs\core\injector\injector.js:74:9)
at async Promise.all (index 0)
at InstanceLoader.createInstancesOfProviders (c:\codelab\nestlab\node_modules\@nestjs\core\injector\instance-loader.js:44:9)
at c:\codelab\nestlab\node_modules\@nestjs\core\injector\instance-loader.js:29:13
the problem is while I set AuthMiddleware on my AppModule constructor like this
constructor(consumer: MiddlewareConsumer) {
consumer
.apply(AuthMiddleware)
.forRoutes({
path: '*',
method: RequestMethod.GET,
});
}
and this my related code.
AuthMiddleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class AuthMiddleware implements NestMiddleware {
use(req: any, res: any, next: () => void) {
console.log('AuthMiddleware passed');
next();
}
}
app.module.ts
import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthMiddleware } from './auth.middleware';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor(consumer: MiddlewareConsumer) {
consumer
.apply(AuthMiddleware)
.forRoutes({
path: '*',
method: RequestMethod.GET,
});
}
}
Thanks for your attention & your help.
CodePudding user response:
the Object is provider
means that you're injecting using an interface (the MiddlewareConsumer
one)
If you read the docs on middleware consumer, you'll notice that the
consumer: MiddlewareConsumer
parameter
should be used in configure
method, not in constructor
Also, do this to improve the type checking:
class AppModule implements NestModule {}