简体   繁体   English

node.js快速递归路由失败(404)

[英]nodejs express recursive routing fails (404)

I started a new node project and wanted to dynamically add routes. 我启动了一个新的节点项目,并希望动态添加路由。 I have done that before, but never went more into depth than one level of folders. 我之前已经做过,但是深度从未超过一层文件夹。 For this purpose, I came up with a recursive function to add the routes und traverse through possible subfolders. 为此,我想出了一个递归函数来添加通过可能的子文件夹进行遍历的路径。 The function is called in my app.js. 该函数在我的app.js中调用。 The project folder looks like this: 项目文件夹如下所示:

app.js
routes/
    index.js
    users.js
    api/
        foo.js
        test/
            bar.js

The definition and call of the function in app.js: app.js中函数的定义和调用:

var express = require('express');
var fs = require('fs');
var path = require('path');
var app = express();

// Works
var routes = require('./routes/index');
app.use('/', routes);


// 404
getRoutes('routes');

function getRoutes(dir, cur) {
    if(cur === undefined) {
        cur = '/';
    }
    routes = fs.readdirSync(path.join(__dirname, dir));
    routes.forEach( function (file) {

        fs.stat(dir + "/" + file, function (err, stats) {
            if (err) {
                console.log(err);
            }
            else if (stats.isFile()) {
                var routeFilePath = "./" + path.join(dir, file);
                var route = path.join(cur, file.replace(/\.[^/.]+$/, ""))+'/';
                if(file == 'index.js') {
                    route = cur;
                }
                console.log(route, "defined in:", routeFilePath);

                var routeFile = require(routeFilePath);
                app.use(route, routeFile);
            }
            else if (stats.isDirectory()) {
                getRoutes(path.join(dir, file), path.join(cur, file));
            }
        });
    });
}

Please notice, that the direct call of app.use() works. 请注意,直接调用app.use()起作用。 Does anyone see the error? 有人看到错误了吗?

The Output of console.log(route, "defined in:", routeFilePath); console.log(route, "defined in:", routeFilePath); :

/ defined in: ./routes/index.js
/users/ defined in: ./routes/users.js
/api/foo/ defined in: ./routes/api/foo.js
/api/test/bar/ defined in: ./routes/api/test/bar.js

looks correct to me. 对我来说看起来很正确。

The problem was fs.stats() is async. 问题是fs.stats()是异步的。 The routes have to be defined synchronously like: 路由必须同步定义,例如:

function getRoutes(dir, cur) {
    if(cur === undefined) {
        cur = '/';
    }
    routes = fs.readdirSync(path.join(__dirname, dir));
    routes.forEach( function (file) {

        var stats = fs.statSync(dir + "/" + file);
        if (stats.isFile()) {
            var routeFilePath = "./" + path.join(dir, file);
            var route = path.join(cur, file.replace(/\.[^/.]+$/, ""))+'/';
            if(file == 'index.js') {
                route = cur;
            }
            console.log(route, "defined in:", routeFilePath);

            var routeFile = require(routeFilePath.replace(/\.[^/.]+$/, ""));
            console.log(routeFile);
            app.use(route, routeFile);
        }
        else if (stats.isDirectory()) {
            getRoutes(path.join(dir, file), path.join(cur, file));
        }

    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM