NodeJS 在Nest Js ServeStaticModule之前运行中间件

wsewodh2  于 2023-02-03  发布在  Node.js
关注(0)|答案(1)|浏览(141)

我想在Nest JS使用ServeStatic模块为React应用程序提供服务之前运行中间件。我无法在除“/”以外的任何静态路由上运行Nest中间件,甚至全局中间件
main.ts

app.use([AuthRedirectMiddleware, VerifyMiddleware]);

// Or even a simple logger

app.use(function (req, res, next) {
   console.log("LOG: ", req.originalUrl);
   next();
});

// All 3 middlewares only run for / and /api*
// Does not run for /posts , /orders/123 (both are front end routes)

这仅适用于API路由和“/”
我的静态服务器模块是这样设置的:
app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot(),
    ServeStaticModule.forRoot({
      rootPath: clientPath,
      exclude: ["/api*"],
    }),
    SharedModule,
    ...
  ],
  controllers: [],
  providers: [],
})

在main.js中,我还有一个用于API路由的globalPrefix,因此除了/api*之外的所有url都将转到react应用程序

app.setGlobalPrefix("api");
pgky5nke

pgky5nke1#

尝试中间件模块:
my-middleware.module.ts

@Module({}) // you can import/provide anything you need in your module here
export class MyMiddlewareModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer.apply(MyMiddleware).forRoutes('*');
    }
}

@Injectable()
class MyMiddleware implements NestMiddleware {
    async use(req: Request, res: Response, next: (error?: any) => void) {
    
    }
}

然后导入到app.module.ts中:

@Module({
  imports: [
    ConfigModule.forRoot(),
    MyMiddleware, // Important for it to be before your static module
    ServeStaticModule.forRoot({
      rootPath: clientPath,
      exclude: ["/api*"],
    }),
    SharedModule,
    ...
  ],
  controllers: [],
  providers: [],
})

这两个链接也可能有用:

相关问题