您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何将所有路由重定向到nest.js中的index.html(角)?

如何将所有路由重定向到nest.js中的index.html(角)?

您只能使用setBaseViewsDir@Render()与像车把(HBS)视图引擎; 用于提供静态文件(角度),但是,您只能使用useStaticAssetsresponse.sendFile

要使用index.html其他所有路线,您有两种可能:

您可以创建执行重定向的中间件,请参阅本文

@Middleware()
export class FrontendMiddleware implements NestMiddleware {
  resolve(...args: any[]): ExpressMiddleware {
    return (req, res, next) => {
      res.sendFile(path.resolve('../frontend/dist/my-app/index.html')));
    };
  }
}

然后为所有路由注册中间件:

export class ApplicationModule implements NestModule {
  configure(consumer: MiddlewaresConsumer): void {
    consumer.apply(FrontendMiddleware).forRoutes(
      {
        path: '/**', // For all routes
        method: RequestMethod.ALL, // For all methods
      },
    );
  }
}

您可以将所有重定向NotFoundExceptionsindex.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

app.useGlobalFilters(new NotFoundExceptionFilter());
其他 2022/1/1 18:14:34 有458人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶