gpt4 book ai didi

javascript - 根据 req.headers 导入动态文件夹 ['accept-language' ]

转载 作者:行者123 更新时间:2023-12-01 00:32:51 28 4
gpt4 key购买 nike

我正在尝试实现一项新功能 - 使用 Nodejs 发送多语言邮件。

我的目录结构是这样的:

mail-templates
__index.js
__jp
____index.js
____mail1.js
____mail2.js
__en
____index.js
____mail1.js
____mail2.js

enjpindex中,我将导入和导出当前文件夹中的所有文件

mail-teamplatesindex 中,我想根据 req.headers['accept-language'] 动态导入文件夹,例如这个:

import * as Mail from `./${variable}` // variable are en or jp depending on accept-language

我的问题:我怎样才能做到这一点?我如何在这里获取接受语言来动态导入文件夹?

最佳答案

不建议在 http 回调中执行此操作。解决您的问题的最佳解决方案是导入所有可用语言,并为每个请求使用首选语言。

示例:

在您的mail-templates/index.js中:

import * as en from './en';
import * as es from './es';

const defaultLanguage = 'en';
const availableLanguages = { en, es };

function getMailByLanguage(language) {
return availableLanguages[language] || availableLanguages[defaultLanguage];
}

module.exports = getMailByLanguage;

当你想使用它时,只需这样做:

import * as MailTemplates from './mail-templates';

app.get("/", (req, res) => {
const language = req.headers["language"];
const Mail = MailTemplates.getMailByLanguage(language);

// Do your stuff's here
...
});

关于javascript - 根据 req.headers 导入动态文件夹 ['accept-language' ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363605/

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