nestjs - 如何在 Nest.js 中间件中使用服务
问题描述
我需要在一些中间件中使用HttpService
from@nestjs/axios
来验证验证码响应。
我已经app.module.ts
像这样注册了中间件:
@Module({
// ...
controllers: [AppController],
providers: [AppService, HttpService] <---- added HttpService here
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(CaptchaMiddleware)
.forRoutes(
{ path: '/users', method: RequestMethod.POST }
);
}
}
这captcha.middleware.ts
看起来像:
@Injectable()
export class CaptchaMiddleware implements NestMiddleware {
constructor(
private readonly httpService: HttpService
) { }
async use(req: Request, res: Response, next: NextFunction) {
// ... code to verify captcha ...
}
}
但我得到这个错误:
ERROR [ExceptionHandler] Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument AXIOS_INSTANCE_TOKEN at index [0] is available in the AppModule context.
Potential solutions:
- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current AppModule?
- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within AppModule?
@Module({
imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
})
HttpService
添加为依赖项的正确方法是CaptchaMiddleware
什么?
解决方案
您应该导入HttpModule
,而不是提供HttpService
. 就像它在文档中描述的一样。当您提供提供者时,Nest 会尝试创建该提供者的实例,当您导入模块时,Nest 将重新使用提供者(如果存在)或使用模块的提供者定义创建一个新的提供者。
推荐阅读
- python - urllib.request.urlopen 不向列表返回任何内容并引发 indexerror
- yii2 - 使用来自 Gridview Yii2 的数据将数据导出到 excel
- django - 我不确定如何请求 Django rest-framework Social Oauth2
- java - 如何为一个孩子设置多个对象?
- python - 我如何用百分比打印差异
- javascript - 为什么不是
尽管设置了一些 JS 代码,但我的复选框上的属性仍然有效? - prometheus - 获取 http://host-ip:9100/metrics: 超出上下文期限,
- python - 当 matplotlib 从 csv 文件中绘制实时数据时,RAM 迅速增加
- java - 需要关于 Spring Boot API 的错误处理的建议或更好的设计 - 微服务
- design-patterns - 域驱动实现 - 更新聚合根中的单个属性