node.js 如何在 Express 的多个文件中包含路由处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6059246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include route handlers in multiple files in Express?
提问by rafidude
In my NodeJS expressapplication I have app.jsthat has a few common routes. Then in a wf.jsfile I would like to define a few more routes.
在我的 NodeJSexpress应用程序中,我有app.js一些常见的路由。然后在一个wf.js文件中我想定义更多的路由。
How can I get app.jsto recognize other route handlers defined in wf.jsfile?
如何app.js识别wf.js文件中定义的其他路由处理程序?
A simple requiredoes not seem to work.
一个简单的要求似乎不起作用。
回答by BFil
If you want to put the routes in a separate file, for example routes.js, you can create the routes.jsfile in this way:
例如,如果要将路由放在单独的文件中,则routes.js可以通过routes.js以下方式创建文件:
module.exports = function(app){
app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});
//other routes..
}
And then you can require it from app.jspassing the appobjectin this way:
然后你可以要求它以这种方式app.js传递app对象:
require('./routes')(app);
Have also a look at these examples
也看看这些例子
https://github.com/visionmedia/express/tree/master/examples/route-separation
https://github.com/visionmedia/express/tree/master/examples/route-separation
回答by ShortRound1911
Even though this an older question I stumbled here looking for a solution to a similar issue. After trying some of the solutions here I ended up going a different direction and thought I would add my solution for anyone else who ends up here.
尽管这是一个较旧的问题,但我在这里偶然发现了类似问题的解决方案。在尝试了这里的一些解决方案后,我最终走向了不同的方向,并认为我会为其他最终到达这里的人添加我的解决方案。
In express 4.x you can get an instance of the router object and import another file that contains more routes. You can even do this recursively so your routes import other routes allowing you to create easy to maintain url paths. For example if I have a separate route file for my '/tests' endpoint already and want to add a new set of routes for '/tests/automated' I may want to break these '/automated' routes out into a another file to keep my '/test' file small and easy to manage. It also lets you logically group routes together by URL path which can be really convenient.
在 express 4.x 中,您可以获得路由器对象的实例并导入另一个包含更多路由的文件。您甚至可以递归地执行此操作,以便您的路由导入其他路由,从而允许您创建易于维护的 url 路径。例如,如果我的“/tests”端点已经有一个单独的路由文件,并且想要为“/tests/automated”添加一组新的路由,我可能想将这些“/automated”路由分解到另一个文件中保持我的“/test”文件小而易于管理。它还允许您通过 URL 路径将路由逻辑分组在一起,这非常方便。
Contents of ./app.js:
./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);
Contents of ./routes/tests.js
./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;
Contents of ./routes/testRoutes/automated.js:
./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;
回答by Sam Corder
Building on @ShadowCloud 's example I was able to dynamically include all routes in a sub directory.
以@ShadowCloud 的示例为基础,我能够将所有路由动态包含在子目录中。
routes/index.js
路线/ 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);
});
}
Then placing route files in the routes directory like so:
然后将路由文件放置在路由目录中,如下所示:
routes/test1.js
路线/test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
Repeating that for as many times as I needed and then finally in app.jsplacing
根据需要重复多次,然后最后在app.js 中放置
require('./routes')(app);
回答by Brad Proctor
And build yet more on the previous answer, this version of routes/index.js will ignore any files not ending in .js (and itself)
并在上一个答案的基础上进一步构建,此版本的 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);
});
}
回答by infinity1975
Full recursive routing of all .jsfiles inside /routesfolder, put this in app.js.
.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
in /routesyou put whatevername.jsand initialize your routes like this:
在/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' });
});
}
回答by Sukma Saputra
I am trying to update this answer with "express": "^4.16.3". This answer is the similar as ShortRound1911.
我试图用“express”:“^4.16.3”更新这个答案。这个答案与 ShortRound1911 类似。
server.js
服务器.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);
});
});
/src/routes/index.js
/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;
/src/routes/siswa_route.js
/src/routes/siswa_route.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.json({item: 'Siswa page...'});
});
module.exports = app;
I hope this can help someone. Happy coding!
我希望这可以帮助某人。快乐编码!
回答by gihanchanuka
If you're using express-4.xwith TypeScriptand ES6, this would be the best template to use:
如果您使用快递,4.x版与打字稿和ES6,这将是使用的最佳模板:
src/api/login.ts
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;
src/app.ts
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");
});
Much cleaner than using varand module.exports.
比使用varand干净得多module.exports。
回答by NiallJG
If you want a separate .js file to better organize your routes, just create a variable in the app.jsfile pointing to its location in the filesystem:
如果你想要一个单独的 .js 文件来更好地组织你的路由,只需在app.js文件中创建一个变量,指向它在文件系统中的位置:
var wf = require(./routes/wf);
then,
然后,
app.get('/wf', wf.foo );
where .foois some function declared in your wf.jsfile. e.g
.foo在您的wf.js文件中声明的某个函数在哪里。例如
// wf.js file
exports.foo = function(req,res){
console.log(` request object is ${req}, response object is ${res} `);
}
回答by Mike S.
I know this is an old question, but I was trying to figure out something like for myself and this is the place I ended up on, so I wanted to put my solution to a similar problem in case someone else has the same issues I'm having. There's a nice node module out there called consignthat does a lot of the file system stuff that is seen here for you (ie - no readdirSync stuff). For example:
我知道这是一个老问题,但我试图为自己找出类似的东西,这就是我结束的地方,所以我想把我的解决方案放在一个类似的问题上,以防其他人有同样的问题我'我有。有一个很好的节点模块,叫做consign,它可以为您完成很多在这里看到的文件系统内容(即 - 没有 readdirSync 内容)。例如:
I have a restful API application I'm trying to build and I want to put all of the requests that go to '/api/*' to be authenticated and I want to store all of my routes that go in api into their own directory (let's just call it 'api'). In the main part of the app:
我有一个安静的 API 应用程序,我正在尝试构建,我想将所有进入“/api/*”的请求都进行身份验证,我想将所有进入 api 的路由存储到它们自己的目录中(让我们称之为'api')。在应用程序的主要部分:
app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));
Inside of the routes directory, I have a directory called "api" and a file called api.js. In api.js, I simply have:
在路由目录中,我有一个名为“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;
Everything worked as expected. Hope this helps someone.
一切都按预期进行。希望这可以帮助某人。
回答by regretoverflow
One tweak to all of these answers:
对所有这些答案的一个调整:
var routes = fs.readdirSync('routes')
.filter(function(v){
return (/.js$/).test(v);
});
Just use a regex to filter via testing each file in the array. It is not recursive, but it will filter out folders that don't end in .js
只需使用正则表达式通过测试数组中的每个文件来过滤。它不是递归的,但会过滤掉不以 .js 结尾的文件夹

