Node.js 找不到Express、i18n和自定义页面

Node.js 找不到Express、i18n和自定义页面,node.js,express,internationalization,i18n-node,Node.js,Express,Internationalization,I18n Node,我正在构建一个供个人使用的Express应用程序,但我希望它支持多种语言。我使用的是英语(en)和西班牙语(es),并编写了两条路线,如下所示: function setLanguage (req, res, next) { const locales = i18n.getLocales() const { lang } = req.params if (locales.includes(lang)) { req.setLocale(lang) return nex

我正在构建一个供个人使用的Express应用程序,但我希望它支持多种语言。我使用的是英语(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/
它也会显示未找到的页面


所以问题是,如何设置一个带有自定义未找到页面的多语言应用程序?

您必须首先选择一个默认语言。我认为您可以为以前的访问设置cookie,以从req头检查新请求的区域设置。还有一个选项是,您可以在未找到的页面上提供多语言选择,以便用户可以手动更改i18n配置中设置的默认语言。我脑子里有cookies,但正如你所说,它需要用户之前的访问。我要看一下
req.headers
。谢谢:)