在express中缺少语言环境文件时提供404

时间:2015-01-24 07:01:25

标签: node.js express yeoman-generator-angular i18next

我使用的是DaftMonk的generator-angular-fullstack,除了我遇到的一个小问题外,它很棒......

我使用i18next来处理本地化,以及库的工作方式是它尝试从指定的路径加载区域设置文件,以便为用户提供本地化设置,即:/locales/en-US/app.json - 如果不存在,则尝试/locales/en/app.json(在我的情况下,在此处查找文件)。

问题在于生成器的工作方式是它有一个路由捕获,它将所有404重定向到index.html(角应用的入口点)。这允许单页面应用程序的动态路由。

发生这种情况时,i18next会因为期待404或json语言环境文件而窒息,而是获得index.html页面。

如果文件丢失,我需要一种方法来排除/locales路径被此通配符catch all处理并提供404而不是index.html页面。

以下是快速通配符的作用:

//is there anyway to write an exclusion to this `/*` wildcard?
app.route('/*')
    .get(middleware.setUserCookie, index.index);

/**
 * Send our single page app
 */
exports.index = function (req, res) {
    res.render('index', {
        name: pkg.name,
        version: pkg.version,
        env: config.env
    });
};

//in dev mode
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'app')));

//in production mode
app.use(express.static(path.join(config.root, 'public')));

如果找不到文件,如何编写将/locales/*重定向到404的规则,而不是重定向到index.html

1 个答案:

答案 0 :(得分:0)

怎么样?
if (/\/locales\//.test(req.originalUrl) {
    send404function()
}

也许这不是app.use(),但希望你不必这么做。