node.js和express:可能从路由回跳到中间件(静态)?

在使用express服务器编写node.js时,我想首先在静态中间件之前运行路由中间件(希望在静态内容服务之前完全控制req / res)。

现在,我还在末尾使用了匹配*的路由,简单地返回一个404.很明显,因为我没有静态内容的路由,所以我需要为我的静态(公共)文件夹添加路由。 当我这样做的时候,我想把路由里面的控制权交给静态中间件,从而跳过我的404路由。 那可能吗? 我读了我可以调用next(“路由”),但是这给了我和调用next()相同的结果。

谢谢

您不需要明确添加*路由。 Express会为你做一个404。

所有你需要做的就是告诉express在静态中间件之前运行自定义路由。 你这样做是这样的:

 app.use(app.router); app.use(express.static(__dirname + '/public'); 

我不知道这是否有帮助,但如果你想要的是有select地logging或拒绝静态文件下载,你可以这样做:

首先,确保在静态中间件之前执行路由:

 app.configure(function(){ ... app.use(app.router); // this one goes first app.use(express.static(__dirname + '/public')); ... 

其次,注册一条捕获所有请求的路由并且只是有条件地做出回应。 以下示例将在下载file-A.txt(其中的文件系统path为/public/file-A.txt)时检测并logging一条消息,其他文件请求将不会中断下载:

 app.get('/*', function(req, res, next){ if(req.params[0] === 'file-A.txt') { // you can also use req.uri === '/file-A.txt' // Yay this is the File A... console.warn("The static file A has been requested") // but we still let it download next() } else { // we don't care about any other file, let it download too next() } }); 

就是这样,我希望这有助于。