繁体   English   中英

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

[英]How to redirect all routes to index.html (Angular) in nest.js?

我正在制作 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);
}

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') 请帮忙

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

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

A) 中间件

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

@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
      },
    );
  }
}

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')));
  }
}

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

app.useGlobalFilters(new NotFoundExceptionFilter());

2019 年 12 月 10 日的更新答案

您需要创建中间件来发送 react index.html

创建中间件文件

前端.middleware.ts

import { NestMiddleware, Injectable } from '@nestjs/common';
import {Request, Response} from "express"
import { resolve } from 'path';

@Injectable()
export class FrontendMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    res.sendFile(resolve('../../react/build/index.html'));
  }
}

包括中间件

app.module.ts

import { FrontendMiddleware } from './frontend.middleware';
import {
  Module,
  MiddlewareConsumer,
  RequestMethod,
} from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {
  configure(frontEnd: MiddlewareConsumer) {
    frontEnd.apply(FrontendMiddleware).forRoutes({
      path: '/**', // For all routes
      method: RequestMethod.ALL, // For all methods
    });
  }
}

供参考的应用程序结构:

在此处输入图片说明

您还可以将 Cloud Functions for Firebase 与 Firebase 托管一起使用。 您在main.ts拥有的内容非常好,使用这种方法您甚至不需要控制器。 你应该按照以下步骤进行:

  1. index.html重命名为index2.html 这对于渲染您的路线路径很重要,否则您将在所有路线上都能正常渲染,不包括根/
  2. 更新angular.json以具有以下"index": "apps/myapp/src/index2.html", (只需将index.html更改为index2.html )。 注意:你的 index.html 路径可能不同,我使用的是Nx workspace
  3. 添加templatePath: join(BROWSER_DIR, 'index2.html'),到 NestJS 的ApplicationModule ,很可能你在服务器目录中将该文件命名为app.module.ts

像这样:

@Module({
  imports: [
    AngularUniversalModule.forRoot({
      bundle: require('./path/to/server/main'), // Bundle is created dynamically during build process.
      liveReload: true,
      templatePath: join(BROWSER_DIR, 'index2.html'),
      viewsPath: BROWSER_DIR
    })
  ]
})
  1. 初始化 Firebase Cloud Functions 和 Firebase Hosting,有关如何设置,您可以查看https://hackernoon.com/deploying-angular-universal-v6-with-firebase-c86381ddd445https://blog.angularindepth.com/angular -5-universal-firebase-4c85a7d00862

  2. 编辑您的firebase.json

它应该看起来像那样,或者至少是hosting部分。

{
  "hosting": {
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "public": "functions/dist/apps/path/to/browser",
    "rewrites": [
      {
        "function": "angularUniversalFunction",
        "source": "**"
      }
    ]
  }
} 
  1. main.ts 中,您需要在服务器上设置 Cloud Functions。

在简约的情况下,它会像这样:

import * as admin from 'firebase-admin';
import * as functions from 'firebase-functions';

admin.initializeApp(); // Initialize Firebase SDK.
const expressApp: Express = express(); // Create Express instance.

// Create and init NestJS application based on Express instance.
(async () => {
  const nestApp = await NestFactory.create<NestExpressApplication>(
    ApplicationModule,
    new ExpressAdapter(expressApp)
  );
  nestApp.init();
})().catch(err => console.error(err));

// Firebase Cloud Function for Server Side Rendering (SSR).
exports.angularUniversalFunction = functions.https.onRequest(expressApp);

使用这种方法,您不必关心 NestJS 端的路由。 您可以在 Angular 端设置所有内容,仅此而已。 Angular 负责路由。 您可能已经注意到这是服务器端渲染 (SSR),但是可以结合使用 NestJS + Cloud Functions for Firebase 将所有路由重定向到index.html (或更准确地说index2.html )。 另外你有一个“免费”的 SSR :)

展示项目:

1) Angular + Angular Universal (SSR) + Cloud Functions for Firebase: https : //github.com/Ismaestro/angular8-example-app (缺少 NestJS)。

2) Angular + NestJS: https : //github.com/kamilmysliwiec/universal-nest (缺少 Firebase 的云函数)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM