@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-http-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 传递文件,如果在开发模式而不是生产模式下运行,则会失败。
我会在那里寻找解决方案。