![](/img/trans.png)
[英]How to redirect all routes to index.html (Angular) in nest.js?
[英]Excluding all /api routes in Nest.js to serve React app
我正在 Nest.js 中开发一个后端,它应该在所有根级路由( /about
、 /contact-us
等)上提供 React 生成的index.html
,但不在以/api
开头的那些上。 这是我目前在AppController
中所做的:
@Get('/')
@Get('/contact')
@Get('/about-us')
fileServingRoutes(@Res() res: Response) {
return res.sendFile('index.html', { root: AppModule.getStaticAssetsRootPath() });
}
有没有办法在不手动定义所有必须发回文件的路由的情况下做到这一点?
我建议您关注 Bo 关于服务 SPA 的精彩文章。 该设置考虑到了 Angular,但对于 React 应用程序来说也是如此。
定义一个中间件函数,将除/api
之外的所有路由重定向到您的index.html
。
@Middleware()
export class FrontendMiddleware implements NestMiddleware {
use(req, res, next) {
const { url } = req;
if (url.indexOf('/api') === 1) {
next();
} else {
res.sendFile(resolvePath('index.html'));
}
}
}
在你的AppModule
为所有路由注册它:
export class ApplicationModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(FrontendMiddleware).forRoutes(
{
path: '/**',
method: RequestMethod.ALL,
},
);
}
}
我根据我的需要稍微修改了 Kim 的解决方案(我使用的是 5.8.0 版),因此如果您收到中间件没有正确实现NestMiddleware
接口的错误(由于resolve
方法),您可以使用功能中间件;
export function FrontendMiddleware(req, res, next) {
const { baseUrl } = req;
if (baseUrl.indexOf('/api') === 0) {
next();
} else {
res.sendFile(<path to your index.html file>);
}
}
我还使用baseUrl
而不是url
属性,当我尝试访问/api
路由时返回/
。
您也可以考虑使用@nestjs/serve-static 包。 它可以帮助您提供静态内容,例如 React 和其他 SPA。
该配置有一个选项来排除您要排除的路由。
例如,您可以使用“api”作为 API 路由的前缀:
app.setGlobalPrefix('api')
并使用来自 @nestjs/serve-static 的 ServeStaticModule 为您的 React 提供服务。
AppModule 中的一个基本配置:
... @Module({ imports: [ ServeStaticModule.forRoot({ rootPath: join(__dirname, '..', 'client'), exclude: ['api/*'], }), ], controllers: [AppController], providers: [AppService], }) export class AppModule {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.