在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。
如何让app.js识别在wf.js文件中定义的其他路由处理程序?
一个简单的要求似乎不起作用。
在我的NodeJS express应用程序中,我有app.js,它有一些常见的路由。然后在wf.js文件中,我想定义更多的路由。
如何让app.js识别在wf.js文件中定义的其他路由处理程序?
一个简单的要求似乎不起作用。
当前回答
如果你想要一个单独的.js文件来更好地组织你的路由,只需在app.js文件中创建一个变量,指向它在文件系统中的位置:
var wf = require(./routes/wf);
然后,
app.get('/wf', wf.foo );
其中.foo是wf.js文件中声明的某个函数。如
// wf.js file
exports.foo = function(req,res){
console.log(` request object is ${req}, response object is ${res} `);
}
其他回答
基于@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);
如果你想把路由放在一个单独的文件中,例如routes.js,你可以这样创建routes.js文件:
module.exports = function(app){
app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});
//other routes..
}
然后你可以从app.js中以这样的方式传递app对象:
require('./routes')(app);
看看这些例子:https://github.com/visionmedia/express/tree/master/examples/route-separation
所有这些答案的一个调整:
var routes = fs.readdirSync('routes')
.filter(function(v){
return (/.js$/).test(v);
});
只需使用正则表达式通过测试数组中的每个文件进行筛选。它不是递归的,但它会过滤掉不以.js结尾的文件夹
如果你使用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干净多了。
您可以将所有路由函数放在其他文件(模块)中,并将其链接到主服务器文件。 在main express文件中,添加一个将模块链接到服务器的函数:
function link_routes(app, route_collection){
route_collection['get'].forEach(route => app.get(route.path, route.func));
route_collection['post'].forEach(route => app.post(route.path, route.func));
route_collection['delete'].forEach(route => app.delete(route.path, route.func));
route_collection['put'].forEach(route => app.put(route.path, route.func));
}
并为每个路由模型调用该函数:
link_routes(app, require('./login.js'))
在模块文件(例如- login.js文件)中,像往常一样定义函数:
const login_screen = (req, res) => {
res.sendFile(`${__dirname}/pages/login.html`);
};
const forgot_password = (req, res) => {
console.log('we will reset the password here')
}
然后用request方法导出它作为键,值是一个对象数组,每个对象都有路径和功能键。
module.exports = {
get: [{path:'/',func:login_screen}, {...} ],
post: [{path:'/login:forgotPassword', func:forgot_password}]
};