如何在Express中的多个文件中包含路由处理程序?

raf*_*ude 199 node.js express

在我的NodeJS express应用程序中,我有app.js一些常见的路由.然后在一个wf.js文件中我想定义更多的路线.

如何app.js识别wf.js文件中定义的其他路由处理程序?

一个简单的要求似乎不起作用.

BFi*_*Fil 363

例如,如果要将路径放在单独的文件中,则routes.js可以通过routes.js以下方式创建文件:

module.exports = function(app){

    app.get('/login', function(req, res){
        res.render('login', {
            title: 'Express Login'
        });
    });

    //other routes..
}
Run Code Online (Sandbox Code Playgroud)

然后你可以app.js通过这种方式传递app 对象来要求它:

require('./routes')(app);
Run Code Online (Sandbox Code Playgroud)

还看看这些例子

https://github.com/visionmedia/express/tree/master/examples/route-separation

  • 实际上,作者(TJ Holowaychuck)提供了更好的方法:http://vimeo.com/56166857 (18认同)
  • 不知怎的,这个答案清除了我对module.exports的很多问题.惊人. (7认同)
  • 如果你需要一些函数,只需将它们放入另一个模块/文件中,并从app.js和routes.js中获取它 (5认同)
  • 有更好的回答下面这个问题 - http://stackoverflow.com/a/37309212/297939 (5认同)
  • 我理解所有听到的但是要求('./ routes')(app)这个syntex让我大吃一惊,任何人都可以告诉我这到底是什么,或者我知道它的传递app对象"app"有什么用处 (2认同)
  • @RishabhAgrawal 它看起来比实际情况更复杂。`require('./routes')` 部分将导入在单独文件中创建的函数。`(app)` 部分将以 `app` 作为参数调用该函数。将函数导入为 `const paths = require('./routes')`,然后将其调用为 `routes(app)` 可能更容易理解。 (2认同)

Sho*_*911 98

即使这是一个较老的问题,我在这里偶然发现了寻找类似问题的解决方案.在尝试了一些解决方案之后,我最终走向了一个不同的方向,并认为我会为其他任何人在这里添加我的解决方案.

在express 4.x中,您可以获取路由器对象的实例并导入包含更多路由的另一个文件.您甚至可以递归执行此操作,以便您的路由导入其他路由,从而允许您创建易于维护的URL路径.例如,如果我已经为我的'/ tests'端点有一个单独的路由文件,并且想为'/ tests/automated'添加一组新的路由,我可能想要将这些'/ automated'路由分解为另一个文件到保持我的'/ test'文件小而易于管理.它还允许您通过URL路径将路由逻辑分组,这非常方便.

./app.js的内容:

var express = require('express'),
    app = express();

var testRoutes = require('./routes/tests');

// Import my test routes into the path '/test'
app.use('/tests', testRoutes);
Run Code Online (Sandbox Code Playgroud)

./routes/tests.js的内容

var express = require('express'),
    router = express.Router();

var automatedRoutes = require('./testRoutes/automated');

router
  // Add a binding to handle '/test'
  .get('/', function(){
    // render the /tests view
  })

  // Import my automated routes into the path '/tests/automated'
  // This works because we're already within the '/tests' route so we're simply appending more routes to the '/tests' endpoint
  .use('/automated', automatedRoutes);

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

./routes/testRoutes/automated.js的内容:

var express = require('express'),
    router = express.Router();

router
   // Add a binding for '/tests/automated/'
  .get('/', function(){
    // render the /tests/automated view
  })

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,应该放在榜首!谢谢 (2认同)

Sam*_*der 95

在@ShadowCloud的例子的基础上,我能够动态地包含子目录中的所有路由.

路线/ index.js

var fs = require('fs');

module.exports = function(app){
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file == "index.js") return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);
    });
}
Run Code Online (Sandbox Code Playgroud)

然后将路由文件放在routes目录中,如下所示:

路线/ test1.js

module.exports = function(app){

    app.get('/test1/', function(req, res){
        //...
    });

    //other routes..
}
Run Code Online (Sandbox Code Playgroud)

重复那个我需要的次数,然后最终在app.js放置

require('./routes')(app);
Run Code Online (Sandbox Code Playgroud)

  • 使用此方法读取目录中的文件与仅需要app.js文件中的路由是否有任何开销? (5认同)
  • 很好,我也使用这种方法,**附加检查文件扩展名**,因为我遇到了swp文件的问题. (3认同)

Bra*_*tor 19

并且在前一个答案上构建更多,这个版本的routes/index.js将忽略任何不以.js结尾的文件(及其本身)

var fs = require('fs');

module.exports = function(app) {
    fs.readdirSync(__dirname).forEach(function(file) {
        if (file === "index.js" || file.substr(file.lastIndexOf('.') + 1) !== 'js')
            return;
        var name = file.substr(0, file.indexOf('.'));
        require('./' + name)(app);
    });
}
Run Code Online (Sandbox Code Playgroud)


inf*_*975 18

.js文件/routes夹内所有文件进行完全递归路由,将其放入app.js.

// Initialize ALL routes including subfolders
var fs = require('fs');
var path = require('path');

function recursiveRoutes(folderName) {
    fs.readdirSync(folderName).forEach(function(file) {

        var fullName = path.join(folderName, file);
        var stat = fs.lstatSync(fullName);

        if (stat.isDirectory()) {
            recursiveRoutes(fullName);
        } else if (file.toLowerCase().indexOf('.js')) {
            require('./' + fullName)(app);
            console.log("require('" + fullName + "')");
        }
    });
}
recursiveRoutes('routes'); // Initialize it
Run Code Online (Sandbox Code Playgroud)

/routes你在这里放置whatevername.js并初始化你的路线:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index', { title: 'index' });
    });

    app.get('/contactus', function(req, res) {
        res.render('contactus', { title: 'contactus' });
    });
}
Run Code Online (Sandbox Code Playgroud)


gih*_*uka 18

如果您使用快递,4.x版打字稿和ES6,这将是使用的最佳模板:

src/api/login.ts

import express, { Router, Request, Response } from "express";

const router: Router = express.Router();
// POST /user/signin
router.post('/signin', async (req: Request, res: Response) => {
    try {
        res.send('OK');
    } catch (e) {
        res.status(500).send(e.toString());
    }
});

export default router;
Run Code Online (Sandbox Code Playgroud)

src/app.ts

import express, { Request, Response } from "express";
import compression from "compression";  // compresses requests
import expressValidator from "express-validator";
import bodyParser from "body-parser";
import login from './api/login';

const app = express();

app.use(compression());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());

app.get('/public/hc', (req: Request, res: Response) => {
  res.send('OK');
});

app.use('/user', login);

app.listen(8080, () => {
    console.log("Press CTRL-C to stop\n");
});
Run Code Online (Sandbox Code Playgroud)

比使用varand干净得多module.exports

  • 这是我在 2022 年最终使用的答案,谢谢! (4认同)

Suk*_*tra 7

我正在尝试使用“ express”:“ ^ 4.16.3”更新此答案。该答案与ShortRound1911类似。

server.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const db = require('./src/config/db');
const routes = require('./src/routes');
const port = 3001;

const app = new express();

//...use body-parser
app.use(bodyParser.urlencoded({ extended: true }));

//...fire connection
mongoose.connect(db.url, (err, database) => {
  if (err) return console.log(err);

  //...fire the routes
  app.use('/', routes);

  app.listen(port, () => {
    console.log('we are live on ' + port);
  });
});
Run Code Online (Sandbox Code Playgroud)

/src/routes/index.js

const express = require('express');
const app = express();

const siswaRoute = require('./siswa_route');

app.get('/', (req, res) => {
  res.json({item: 'Welcome ini separated page...'});
})
.use('/siswa', siswaRoute);

module.exports = app;
Run Code Online (Sandbox Code Playgroud)

/src/routes/siswa_route.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.json({item: 'Siswa page...'});
});

module.exports = app;
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助某人。编码愉快!


reg*_*low 5

对所有这些答案进行一次调整:

var routes = fs.readdirSync('routes')
      .filter(function(v){
         return (/.js$/).test(v);
      });
Run Code Online (Sandbox Code Playgroud)

只需使用正则表达式通过测试数组中的每个文件进行过滤.它不是递归的,但它会过滤掉不以.js结尾的文件夹


Nia*_*lJG 5

如果您想要一个单独的.js文件来更好地组织您的路线,只需在app.js文件中创建一个变量,使其指向文件系统中的位置即可:

var wf = require(./routes/wf);
Run Code Online (Sandbox Code Playgroud)

然后,

app.get('/wf', wf.foo );
Run Code Online (Sandbox Code Playgroud)

文件中.foo声明的函数在哪里wf.js?例如

// wf.js file 
exports.foo = function(req,res){

          console.log(` request object is ${req}, response object is ${res} `);

}
Run Code Online (Sandbox Code Playgroud)


Mik*_* S. 5

我知道这是一个老问题,但我试图找出类似于我自己的东西,这是我最终的地方,所以我想把我的解决方案解决一个类似的问题以防其他人有同样的问题我'我有.有一个很好的节点模块叫做consign,它可以为你提供很多文件系统的东西(比如 - 没有readdirSync的东西).例如:

我有一个宁静的API应用程序,我正在尝试构建,我想将所有进入'/ api/*'的请求进行身份验证,我想将我在api中的所有路由存储到他们自己的目录中(我们称之为'api').在应用程序的主要部分:

app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));
Run Code Online (Sandbox Code Playgroud)

在routes目录中,我有一个名为"api"的目录和一个名为api.js的文件.在api.js中,我只是:

var express = require('express');
var router = express.Router();
var consign = require('consign');

// get all routes inside the api directory and attach them to the api router
// all of these routes should be behind authorization
consign({cwd: 'routes'})
  .include('api')
  .into(router);

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

一切都按预期工作.希望这有助于某人.