在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。
如何让app.js识别在wf.js文件中定义的其他路由处理程序?
一个简单的要求似乎不起作用。
在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。
如何让app.js识别在wf.js文件中定义的其他路由处理程序?
一个简单的要求似乎不起作用。
当前回答
/routes文件夹中所有.js文件的完全递归路由,把它放在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
在/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' });
});
}
其他回答
/routes文件夹中所有.js文件的完全递归路由,把它放在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
在/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' });
});
}
在快车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);
./routes/tests.js的内容:
var express = require('express'),
router = express.Router();
var automatedRoutes = require('./testRoutes/automated');
router
// Add a binding to handle '/tests'
.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;
./routes/testRoutes/ automatic .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;
如果你使用express-4。使用TypeScript和ES6,这将是最好的模板使用:
登录src /火/ 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
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");
});
比使用var和module.exports干净多了。
我知道这是一个老问题,但我一直在为自己寻找答案,而这就是我最后的归宿,所以我想把我的解决方案用在类似的问题上,以防别人有和我一样的问题。有一个很好的节点模块叫做委托,它为你做了很多文件系统的东西,在这里看到(即没有readdirSync的东西)。例如:
我有一个restful API应用程序,我试图构建,我想把所有的请求,去'/ API /*'进行身份验证,我想存储所有的路由,在API到他们自己的目录(让我们只是叫它' API ')。在应用程序的主要部分:
app.use('/api', [authenticationMiddlewareFunction], require('./routes/api'));
在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;
一切都按照预期进行。希望这能帮助到一些人。
基于@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);
});
}
然后将路由文件放在routes目录中,如下所示:
路线/ test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
根据需要重复多次,最后在app.js中放置
require('./routes')(app);