NestJS根据浏览器的语言提供静态文件

时间:2019-05-07 15:46:17

标签: javascript node.js angular nestjs i18next

Nestjs应该基于浏览器中定义的语言来交付Angular应用程序。

Angular应用程序位于dist/public/endist/public/de上。

如果用户正在使用英语浏览器访问/,则nestjs应该从文件夹dist/public/en传递文件。在这种情况下,浏览器中的路径应指向fqdn/en/

我已经在单一语言的Angular App中使用了它:

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useStaticAssets(join(__dirname, 'public'));
  await app.listen(process.env.PORT || 3000);
}
bootstrap();

我还研究了i18next,它看起来很有希望。

但是我不确定这是否是正确的方向。

热烈欢迎任何提示。

2 个答案:

答案 0 :(得分:1)

比静态提供dist文件夹更好的是将 所有 非api路由重定向到index.html,以便Angular SPA可以使用照顾路由。有关更多详细信息,请参见this answer


您可以通过考虑要用来检测用户语言的因素,从上面的链接答案中调整中间件。 ACCEPT-LANGUAGE标头或某个Cookie:

@Middleware()
export class FrontendMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    // Some way of detecting the user's language
    const languages = req.header('ACCEPT-LANGUAGE') || 'en-US';

    if (languages.contains('de-DE')) {
      res.sendFile(join(__dirname, 'public', 'de' ,'index.html'));
    } else {
      res.sendFile(join(__dirname, 'public', 'en', 'index.html'));
    }
  }
}

答案 1 :(得分:0)

@ kim-kern非常感谢您的回答。它把我推向正确的方向。

我现在通过以下方式解决了这个问题: maint.ts将基于全局中间件进行语言检测,并定义文件的静态传递:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as compression from 'compression';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
const i18next = require('i18next');
const middleware = require('i18next-express-middleware');

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  i18next.use(middleware.LanguageDetector).init({
    detection: {
      order: ['path', 'session', 'querystring', 'cookie', 'header'],
    },
  });

  app.use(
    middleware.handle(i18next, {
      ignoreRoutes: ['/api'],
      removeLngFromUrl: false,
    }),
  );

  app.useStaticAssets(join(__dirname, 'public'));
  app.use(compression());
  await app.listen(process.env.PORT || 3000);
}
bootstrap();

我定义了一个自定义中间件,用于检查找到的语言,并基于baseUrl提供正确的index.html文件:

import { NestMiddleware, Injectable } from '@nestjs/common';
import { Request, Response } from 'express';
import { join } from 'path';

@Injectable()
export class FrontendMiddleware implements NestMiddleware {
  use(req: any, res: Response, next: Function) {
    if (req.lng && !req.baseUrl && req.lng.startsWith('de')) {
      res.sendFile(join(__dirname, 'public', 'de', 'index.html'));
    } else if (!req.baseUrl) {
      res.sendFile(join(__dirname, 'public', 'en', 'index.html'));
    } else {
      next();
    }
  }
}

然后,自定义中间件包含在app.module.ts中:

...
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(FrontendMiddleware).forRoutes({
      path: '/**',
      method: RequestMethod.ALL,
    });
  }
}

现在唯一打开的问题是,它尝试始终从固定目录public传递文件,如果在开发模式而不是生产模式下运行,该文件将失败。

我将在那里寻找解决方案。