How to redirect all routes to index.html (Angular)

2019-08-01 12:57发布

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 {};
  }
}

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

1条回答
趁早两清
2楼-- · 2019-08-01 13:38

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.

To serve index.html from all other routes you have a couple of possibilities:

A) Middleware

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

and then register it as a global filter in your main.ts:

app.useGlobalFilters(new NotFoundExceptionFilter());
查看更多
登录 后发表回答