这是一个适合我的解决方案。我希望网站默认为中文。我在导航栏中也有 2 个语言更改按钮(标志图像),它们转到 /en 和 /zh 路由,它们设置 cookie 并将用户重定向回他们来自的页面。
使用隐身窗口和清除 cookie 并刷新站点对其进行了测试。首先在 ZH 中加载,然后通过添加/更改 cookie 值来更改语言。
我还必须在中间件中使用 req.setLocale() 之前初始化 i18n。
const express = require('express');
const hbs = require('express-hbs');
const i18n = require('i18n');
const app = express();
const cookieParser = require('cookie-parser');
const indexRoutes = require('./routes/indexRoutes');
app.engine(
'hbs',
hbs.express4({
partialsDir: __dirname + '/views/partials/',
helpers: {
__: function () {
return i18n.__.apply(this, arguments);
},
__n: function () {
return i18n.__n.apply(this, arguments);
},
},
})
);
app.set('view engine', 'hbs');
app.use(express.json());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(__dirname + '/public'));
i18n.configure({
locales: ['zh', 'en'],
defaultLocale: 'zh',
cookie: 'locale',
directory: __dirname + '/locales',
directoryPermissions: '755',
autoReload: true,
updateFiles: true,
objectNotation: true,
api: {
__: '__', //now req.__ becomes req.__
__n: '__n', //and req.__n can be called as req.__n
},
});
app.use(i18n.init);
app.use((req, res, next) => {
if (req.cookies.locale === undefined) {
res.cookie('locale', 'zh', { maxAge: 900000, httpOnly: true });
req.setLocale('zh');
}
next();
});
app.get('/zh', (req, res) => {
res.cookie('locale', 'zh', { maxAge: 900000, httpOnly: true });
res.redirect('back');
});
app.get('/en', (req, res) => {
res.cookie('locale', 'en', { maxAge: 900000, httpOnly: true });
res.redirect('back');
});
app.use('/', indexRoutes);
app.listen(process.env.PORT || 3000, () =>
console.log(`Server up on ${process.env.PORT || 3000}`)
);