【问题标题】:Excluding all /api routes in Nest.js to serve React app排除 Nest.js 中的所有 /api 路由以服务 React 应用程序
【发布时间】:2019-08-15 12:49:57
【问题描述】:

我正在 Nest.js 中开发一个后端,它应该在所有根级路由(/about/contact-us 等)上提供 React 生成的 index.html,但不适用于以 @987654324 开头的路由@。这是我目前在AppController做的:

@Get('/')
@Get('/contact')
@Get('/about-us')
fileServingRoutes(@Res() res: Response) {
  return res.sendFile('index.html', { root: AppModule.getStaticAssetsRootPath() });
}

有没有办法在不手动定义所有必须发回文件的路由的情况下做到这一点?

【问题讨论】:

    标签: javascript node.js typescript routing nestjs


    【解决方案1】:

    我建议在服务 SPA 方面关注 Bo 的 article。该设置考虑了 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,
          },
        );
      }
    }
    

    【讨论】:

      【解决方案2】:

      我根据我的需要稍微修改了 Kim 的解决方案(我使用的是 5.8.0 版),所以如果您收到中间件未正确实现 NestMiddleware 接口的错误(因为 resolve 方法),你可以使用functional middleware;

      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 路由时返回/

      【讨论】:

      • 您使用的是哪个 Nest 版本?我的解决方案应该是嵌套 v6 语法(它从 v5 更改)。不过我没有测试它。
      • 我使用的是 5.8.0 版本。感谢您的澄清,我会更新我的答案。
      • 好的,我明白了。 :-) 链接的文章使用nest v5 语法,这就是我在帖子中使用v6 语法的原因。您应该考虑更新,这不是一项巨大的努力,但会添加一些不错的新功能(例如,中间件语法更清晰 ;-))docs.nestjs.com/migration-guide
      猜你喜欢
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 2014-11-25
      • 2016-11-23
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多