如何将所有路由重定向到nest.js中的index.html(角)? [英] How to redirect all routes to index.html (Angular) in nest.js?
问题描述
我正在制作Angular + NestJS应用,我想为所有路线发送index.html
文件.
I am making Angular + NestJS app, and I want to send index.html
file for all routes.
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useStaticAssets(join(__dirname, '..', 'frontend', 'dist', 'my-app'));
app.setBaseViewsDir(join(__dirname, '..', 'frontend', 'dist', 'my-app'));
await app.listen(port);
}
app.controller.ts
@Controller('*')
export class AppController {
@Get()
@Render('index.html')
root() {
return {};
}
}
在打开localhost:3000/
时工作正常,但是如果打开localhost:3000/some_route
,则服务器将显示500 internal error
,并显示Can not find html module
.
我正在搜索为什么收到此错误并且所有人都说set default view engine like ejs or pug
的原因,但是我不想使用某些引擎,我只想发送由angular构建的纯html,而不会像res.sendFile('path_to_file')
那样被黑客入侵.请帮助
It works fine while I open localhost:3000/
, but if I open localhost:3000/some_route
the server falls with 500 internal error
and says Can not find html module
.
I was searching why I am getting this error and everyone says set default view engine like ejs or pug
, but I don't want to use some engines, I just want to send plain html built by angular without hacking like res.sendFile('path_to_file')
. Please help
推荐答案
您只能将setBaseViewsDir
和@Render()
与诸如把手(hbs)之类的视图引擎一起使用;用于提供静态文件(Angular),但是,您只能使用useStaticAssets
和response.sendFile
.
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
.
要在所有其他路线上投放index.html
,您可以选择以下几种方式:
To serve index.html
from all other routes you have a couple of possibilities:
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)全局错误过滤器
您可以将所有NotFoundExceptions
重定向到您的index.html
:
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')));
}
}
,然后将其注册为main.ts
中的全局过滤器:
and then register it as a global filter in your main.ts
:
app.useGlobalFilters(new NotFoundExceptionFilter());
这篇关于如何将所有路由重定向到nest.js中的index.html(角)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!