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

eps*_*lon 5 javascript node.js express typescript nestjs

我正在制作 Angular + NestJS 应用程序,我想index.html为所有路由发送文件。

主文件

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);
}
Run Code Online (Sandbox Code Playgroud)

app.controller.ts

@Controller('*')
export class AppController {

  @Get()
  @Render('index.html')
  root() {
    return {};
  }
}
Run Code Online (Sandbox Code Playgroud)

当我打开时它工作正常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'). 请帮忙

Kim*_*ern 6

只能将setBaseViewsDirand@Render()与像handlebars (hbs)这样的视图引擎一起使用;但是,对于提供静态文件(Angular),您只能使用useStaticAssetsresponse.sendFile

要从所有其他路线提供服务,index.html您有几种可能性:

一)中间件

您可以创建一个执行重定向的中间件,请参阅这篇文章

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

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

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

B) 全局错误过滤器

您可以将所有内容重定向NotFoundExceptions到您的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')));
  }
}
Run Code Online (Sandbox Code Playgroud)

然后将其注册为全局过滤器main.ts

app.useGlobalFilters(new NotFoundExceptionFilter());
Run Code Online (Sandbox Code Playgroud)