I want to run a middleware before Nest JS serves my React application using ServeStatic Module. I cannot get a nest middleware or even a Global middleware to run on any static routes other than '/'
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)
This is only working for API routes and '/'
My static serve module is setup like this:
app.module.ts
@Module({
imports: [
ConfigModule.forRoot(),
ServeStaticModule.forRoot({
rootPath: clientPath,
exclude: ["/api*"],
}),
SharedModule,
...
],
controllers: [],
providers: [],
})
I also have a globalPrefix for api routes in main.js. So all urls except for /api*
go to the react application
app.setGlobalPrefix("api");
Try a middleware module:
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) {
}
}
and then import it in your 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: [],
})
Also these two links maybe useful:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.