You can only use setBaseViewsDir
and @Render()
with a view engine like handlebars (hbs); for serving static files (Angular), however, you can only use useStaticAssets
and response.sendFile
.
To serve index.html
from all other routes you have a couple of possibilities:
A) Middleware
You can create a middleware that does the redirect, see this article:
@Middleware()
export class FrontendMiddleware implements NestMiddleware {
resolve(...args: any[]): ExpressMiddleware {
return (req, res, next) => {
res.sendFile(path.resolve('../frontend/dist/my-app/index.html')));
};
}
}
and then register the middleware for all routes:
export class ApplicationModule implements NestModule {
configure(consumer: MiddlewaresConsumer): void {
consumer.apply(FrontendMiddleware).forRoutes(
{
path: '/**', // For all routes
method: RequestMethod.ALL, // For all methods
},
);
}
}
B) Global Error Filter
You can redirect all NotFoundExceptions
to your index.html
:
@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.sendFile(path.resolve('../frontend/dist/my-app/index.html')));
}
}
and then register it as a global filter in your main.ts
:
app.useGlobalFilters(new NotFoundExceptionFilter());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…