在我的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
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)
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)
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。
我正在尝试使用“ 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)
我希望这可以帮助某人。编码愉快!
对所有这些答案进行一次调整:
var routes = fs.readdirSync('routes')
.filter(function(v){
return (/.js$/).test(v);
});
Run Code Online (Sandbox Code Playgroud)
只需使用正则表达式通过测试数组中的每个文件进行过滤.它不是递归的,但它会过滤掉不以.js结尾的文件夹
如果您想要一个单独的.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)
我知道这是一个老问题,但我试图找出类似于我自己的东西,这是我最终的地方,所以我想把我的解决方案解决一个类似的问题以防其他人有同样的问题我'我有.有一个很好的节点模块叫做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)
一切都按预期工作.希望这有助于某人.
| 归档时间: |
|
| 查看次数: |
173009 次 |
| 最近记录: |