Jer*_*lle 5 router express nestjs
在我的 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")
}
}
Run Code Online (Sandbox Code Playgroud)
在我的主模块中:
@Module({
imports: [
ItemsModule, // Other routes like /items
GenericModule, // Generic "*" route last
],
})
Run Code Online (Sandbox Code Playgroud)
它有效,但似乎有点矫枉过正。这是要走的路还是有更简单的技巧?
所以,最好使用global-scoped异常过滤器。
async function bootstrap() {
const app = await NestFactory.create(ApplicationModule);
app.useGlobalFilters(new NotFoundExceptionFilter());
await app.listen(3000);
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)
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`
}
}
Run Code Online (Sandbox Code Playgroud)
可能不行,稍后测试
| 归档时间: |
|
| 查看次数: |
5058 次 |
| 最近记录: |