在express.js路由器中的自定义处理程序

我正在为简单的膳食信息页面工作,我需要在一个过程中运行静态和dynamic(json)服务器,如下所示:

*- root +- index.html +- res | +- main.js | +- index.css | `- (and more) +- meal | `- custom handler here (json reqestes) `- share `- (static files, more) 

静态文件将与express.static处理,我可以路由这与快递?

所有没有以/ meal /开头的请求都应该是静态的,比如/ res或(root)/ anyfolder / anyfile

app.use('/share', express.static('share')); 使静态处理程序在share/查找,而不是项目根目录。 共享整个根是很不寻常的,因为人们可以阅读你的源代码。 你真的需要提供整个文件夹吗? 你可以把res/里面的share/ ,然后做一个符号链接指向res -> share/res/ ,然后当客户端发出请求res/main.js express知道要在share/res/main.js

无论如何@ hexacyanide的代码应该处理你的情况,只要确保命令你的中间件function,使得Express在静态文件之前处理路由function:

 app.use(app.router) app.use('/share', express.static('share')); app.get('/meal/:param', function(req, res) { // use req.params for parameters res.json(/* JSON object here */); }); // if you want to prevent anything else starting with /meal from going to // static just send a response: //app.get('/meal*', function(req, res){res.send(404)} ); app.get('/', function(req, res) { res.sendfile('index.html'); }); 

是的,这可以用Express来完成。 您的设置可能如下所示:

 app.use('/share', express.static('share')); app.get('/', function(req, res) { res.sendfile('index.html'); }); app.get('/meal/:param', function(req, res) { // use req.params for parameters res.json(/* JSON object here */); }); 

如果将静态文件服务器装载到/share并路由到名为/share的目录,则会发送名为index.html的文件的路由以及接受参数的路由,并使用JSON进行响应。

任何未被路由捕获的东西都将被尝试由静态文件服务器处理。 如果文件服务器没有find一个文件,那么它将以404响应。