我正在构建一个供个人使用的 Express 应用程序,但我希望它支持多种语言。我将i18-node用于英语(en)和西班牙语(es),并编写了两条路线,如下所示:
function setLanguage (req, res, next) {
const locales = i18n.getLocales()
const { lang } = req.params
if (locales.includes(lang)) {
req.setLocale(lang)
return next()
}
return next(new Error('Page not found'))
}
app.get('/', setLanguage, (req, res) => {
// Renders the home with 'es' as default locale
res.render('index')
})
app.get('/:lang', setLanguage, (req, res) => {
// Renders the same view with 'es' or 'en' locale
res.render('index')
})
如果我访问localhost:3000/es或localhost:3000/en它的工作原理。如果我访问localhost:3000/thisdoesnotexist它会显示未找到的页面,但如果我访问localhost:3000/它也会显示未找到的页面。
所以问题是,如何设置带有自定义未找到页面的多语言应用程序?