【问题标题】:node.js and express: possible to skip from route back to middleware (static)?node.js 和 express:可以从路由跳回中间件(静态)吗?
【发布时间】:2011-12-07 20:10:33
【问题描述】:

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

现在,我还在末尾使用匹配 * 的路由来简单地返回 404。显然,由于我没有静态内容的路由,我需要为我的静态(公共)文件夹添加路由。这样做时,我想将控制权从路由内部传递给静态中间件,从而跳过我的 404 路由。那可能吗?我读到我可以调用 next("route"),但这给了我与调用 next() 相同的结果。

谢谢

【问题讨论】:

  • 为什么不在static 之后添加您的* 404?

标签: node.js express


【解决方案1】:

您不需要显式添加* 路由。 Express 会为您执行 404。

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

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

【讨论】:

    【解决方案2】:

    我不确定这是否有帮助,但如果您想要有选择地记录或拒绝静态文件下载,您可以这样做:

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

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

    其次,注册一个捕获所有请求并有条件地响应的路由。以下示例在下载 file-A.txt(文件系统路径为 /public/file-A.txt)时检测并记录一条消息,任何其他文件请求都将下载而不会中断:

    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()
        }
    });
    

    就是这样,希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2015-10-05
      • 2015-01-17
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多