快递app在即将到来的路线之前处理404。并非所有已存在的路由都由express.Router及时检测到

时间:2017-05-27 19:41:27

标签: javascript node.js express routing routes

这是app.js文件:

var express = require('express');
var routes = require('./routes/index');
app = express();

app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);  //res.render('404')
});

和routes / index.js:

var express    = require('express')
, router       = express.Router()
var importer = require('./../lib/importer')
    , importRoutes = importer(__dirname)
    , routes = {
        views: importRoutes('./views')
    };

router.get('/login', routes.views.login.get);
router.post('/login', routes.views.login.post);
router.get('/register', routes.views.register.get);
... and many other routes (more than 50)
router.get('/theLastRoute', routes.views.auth.oneOfTheLastRoutes.get);
module.exports = router;

但是如果我从应用程序响应404的底部转到localhost:3000/oneOfTheLastRoutes或某条路线,即使这条路线确实存在于routes / index.js中,如果我在模块中将此路线移到更高位置,该应用程序将给出正确的回应。

我几乎可以确定问题出在lib / importer.js中,其中一些异步代码需要来自routes / views文件夹的所有路由,而不是所有路由都分配给rotutes.view属性。

importer.js:

var fs = require('fs');
var path = require('path');
function dispatchImporter (rel__dirname) {

    function importer (from) {
        //console.log('importing ', from);
        var imported = {};
        var joinPath = function () {
            return '.' + path.sep + path.join.apply(path, arguments);
        };

        var fsPath = joinPath(path.relative(process.cwd(), rel__dirname), from);

        fs.readdirSync(fsPath).forEach(function (name) {
            var info = fs.statSync(path.join(fsPath, name));
            //console.log(name);
            if (info.isDirectory()) {
                imported[name] = importer(joinPath(from, name));
            } else {
                // only import files that we can `require`
                var ext = path.extname(name);
                var base = path.basename(name, ext);
                if (require.extensions[ext]) {
                    imported[base] = require(path.join(rel__dirname, from, name));
                } else {
                    console.log('cannot require ', ext);
                }
            }
        });

        return imported;
    }

    return importer;
}

module.exports = dispatchImporter;

我没有设法提出一个解决方案,在404处理程序之前需要所有路径文件并将其分配给routes对象。

文件结构如下:

app.js
lib/
   importer.js
routes/
   index.js
   views/
      login.js
      register.js
      etc...

1 个答案:

答案 0 :(得分:0)

问题结果发生在其他模块中,其中声明了重叠路线。