6

在我的 Angular 应用程序中,如果我加载主页/然后导航到 ,/products它可以正常工作(它是一个延迟加载的模块)。但是如果现在我重新加载页面,浏览器会GET /products调用服务器,这会导致 404。

解决方案是发送index.html,Angular 应用程序又回到了轨道上。所以在 Express 中我这样做app.all("*", (req,res) => { res.sendFile("index.html") })并且它有效。

如何在 Nest 中做同样的事情?

有一个@All装饰器,但是给定组件中的每个控制器都处理一个子路由,例如@Controller("cats")将匹配/cats路由,所以如果我添加@All这个控制器,它将只匹配/cats/*,而不匹配*

我真的必须为此创建一个带有控制器的完整独立模块吗?这就是我所做的

@Controller() // Matches "/"
export class GenericController {

    @All() // Matches "*" on all methods GET, POST...
    genericFunction(){
        console.log("Generic route reached")
    }
}

在我的主模块中:

@Module({
    imports: [
        ItemsModule, // Other routes like /items
        GenericModule, // Generic "*" route last
    ],
})

它有效,但似乎有点矫枉过正。这是要走的路还是有更简单的技巧?

4

2 回答 2

6

所以,最好使用global-scoped异常过滤器。

async function bootstrap() {
  const app = await NestFactory.create(ApplicationModule);
  app.useGlobalFilters(new NotFoundExceptionFilter());
  await app.listen(3000);
}
bootstrap();

NotFoundExceptionFilter

import { ExceptionFilter, Catch, NotFoundException } from '@nestjs/common';
import { HttpException } from '@nestjs/common';

@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
    catch(exception: HttpException, host: ArgumentsHost) {
        const ctx = host.switchToHttp();
        const response = ctx.getResponse();
        // here return `index.html`
    }
}

可能不行,以后测试

于 2018-04-19T09:28:34.207 回答
2

您无需创建单独的GenericModule. 但是,GenericController是完全有效的,你的方法绝对是一个好方法。问题是您希望使用此通用路线实现什么目标。如果您需要处理“找不到路由”错误,则更好的选择是异常过滤器。

于 2018-04-19T07:08:33.533 回答