使用express.js动态加载路由 [英] Dynamically load routes with express.js
问题描述
我正在将express.js用作Web服务器,并且希望有一种简单的方法来将所有 app.get和 app.post功能分开以分开文件。例如,如果我想为登录页面指定get和post函数,我希望在动态加载的routes文件夹中有一个login.js文件(将自动添加所有文件,而不必指定每个文件),当我运行节点app.js
I am using express.js as a webserver and would like an easy way to separate all the "app.get" and "app.post" functions to separate files. For example, if I would like to specify get and post functions for a login page, I would like to have a login.js file in a routes folder that is dynamically loaded (will automatically add all of the files without having to specify each one) when I run node app.js
我已经尝试过此此解决方案 !,但对我不起作用。
I have tried this this solution!, but it isn't working for me.
推荐答案
app.js
var express=require("express");
var app=express();
var fs=require("fs");
var routePath="./routers/"; //add one folder then put your route files there my router folder name is routers
fs.readdirSync(routePath).forEach(function(file) {
var route=routePath+file;
require(route)(app);
});
app.listen(9123);
我在该文件夹中放置了两个路由器以下
I have put below two routers in that folder
route1.js
route1.js
module.exports=function(app){
app.get('/',function(req,res){
res.send('/ called successfully...');
});
}
route2.js
route2.js
module.exports=function(app){
app.get('/upload',function(req,res){
res.send('/upload called successfully...');
});
}
这篇关于使用express.js动态加载路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!