簡體   English   中英

排除 Nest.js 中的所有 /api 路由以服務 React 應用程序

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM