gpt4 book ai didi

javascript - NestJS 根据浏览器语言传递静态文件

转载 作者:行者123 更新时间:2023-11-29 22:58:57 26 4
gpt4 key购买 nike

Nestjs 应该根据浏览器中定义的语言交付 Angular 应用程序。

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

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

我已经在单语言 Angular 应用程序中使用了它:

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

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

我还查看了 i18next这看起来很有希望。

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

热烈欢迎任何提示。

最佳答案

比静态提供您的 dist 文件夹更好的方法是将所有 非 api 路由重定向到 index.html 以便您的 Angular SPA 可以处理路由。参见 this answer了解更多详情。


您可以根据上面链接的答案调整中间件,方法是考虑要检测用户语言的因素,例如ACCEPT-LANGUAGE header 或某个 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'));
}
}
}

关于javascript - NestJS 根据浏览器语言传递静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56026246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com