【问题标题】:How to serve 2 SPA's from a NestJS Application如何从 NestJS 应用程序提供 2 个 SPA
【发布时间】:2021-01-30 08:40:42
【问题描述】:

我在 NestJS 应用程序中使用 app.useStaticAssets(ui); 来服务我的 SPA。该应用程序正在以信息亭模式的浏览器上运行。

新的信息亭硬件有 2 个屏幕,正面和背面。如果我们可以创建另一个 SPA 并在同一个 NestJS 应用程序上提供它,那将是最简单的。

我查看了 NestJS 文档,尝试检查源代码并搜索相关问题,仅找到提示,使用 res.sendFile(不确定资产)或使用 NestJS 下的 express。

有没有办法在直接的 NestJS 中做到这一点?

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    如果您使用 Express 作为 HTTP 适配器,您始终可以设置多个静态资源并为它们使用不同的前缀

    async function bootstrap() {
      const app = await NestFactory.create<NestExpressApplication>(AppModule);
      app.useStaticAssets(join(__dirname, '..', 'public'));
      app.useStaticAssets( join(__dirname, '..', 'other'), {prefix: '/other/'});
      await app.listen(3000);
    }
    bootstrap();
    

    在这种情况下,如果有人导航到localhost:3000,他们将获得public 文件夹的index.html,但如果他们导航到localhost:3000/other,他们将获得other 文件夹的index.html

    Check more out here

    【讨论】:

      【解决方案2】:

      当尝试使用 Jay 回答中的代码时,它根本不适合我,因为我的 Angular 应用程序中的路由在直接通过服务器访问时会出现 404 错误。这是因为内置的 useStaticAssets() 函数只提供它可以在给定目录中找到的文件,而不是你的 Angular 或 React 路由。

      我强烈建议您查看@nestjs/serve-static,因为它允许您像这样为多个 SPA 提供服务:

      import { Module } from '@nestjs/common';
      import { ServeStaticModule } from '@nestjs/serve-static';
      import { join as joinPath } from 'path';
      
      @Module({
          imports: [
              ServeStaticModule.forRoot(
                  {
                      rootPath: joinPath(__dirname, '..', 'client-admin'),
                      serveRoot: '/admin'
                  },
                  {
                      rootPath: joinPath(__dirname, '..', 'client'),
                  }
              )
      
          ]
      })
      export class AppModule {}
      

      但是,在您开始使用之前,您需要确保您的 SPA 已配置为正确安装在这些 URL 上,否则资源(CSS/JS/等)将只是 404。例如,如果您将您的管理应用程序挂载到/admin/,然后您的index.html 中的所有资源文件URL 也必须以/admin/ 为前缀。

      【讨论】:

      • 我无法让它与 fastify 一起使用。 装饰器 sendFile 已添加出现此错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2019-09-05
      • 1970-01-01
      • 2021-11-17
      • 2021-11-07
      • 2019-07-25
      • 2018-10-17
      相关资源
      最近更新 更多