检查用户是否在Express中打开了静态文件?

4
我正在使用以下方式来提供静态文件:
app.use(express.static('static'));

我有一个index.html文件,还有一堆其他文件在./static/下面,这些文件会显示在http://localhost:8080上。
有没有办法拦截GET请求并找出用户何时打开了静态文件?我尝试过。
app.get('/', (req, res) => { console.log("Opened!") }

但是这并不起作用。


将“/”更改为“/static/:filename”,并且不要将参数传递给express.static()。 - user10408316
@zee,您是想保存历史记录还是只想保存最后一次开启的时间呢? - Saurabh Mistry
我不确定我理解这个问题,但我认为它应该是上次打开的时间。由于我认为静态文件是使用GET请求获取的,所以我希望在任何用户尝试加载文件时得到通知。 - Zee
1个回答

5

编辑:感谢@robertklep对我的解决方案进行了重构,使整个过程更加完美。这是一个更加简洁的解决方案,当任何静态文件被服务并打印其URL时,它会通知您:

const express = require("express");
const app = express();

const static = express.static('static');

app.use(function(req, res, next) {
    // declare a handler for the "request end" event
    function staticReqNotifier() {
        console.log("static file was served", req.url);
    }

    // listen to that event in before the static middleware is invoked
    req.on("end", staticReqNotifier);

    // manually invoke the static middleware with this middleware's arguments
    // we define the static middleware's next function - if it's called, the 
    // resource requested is not static so detach the listener and forward the response
    static(req, res, (err) => {
        req.off("end", staticReqNotifier);
        next(err);
    });
});

// test endpoint so show non-static requests work fine
app.get("/", function(req, res) {
    res.send("test");
});

app.listen(3000);

因为任何显式请求最多只能由一个中间件处理,所以在静态中间件之前监听“请求已结束”事件并在确保静态中间件未处理请求后将其分离就足够了。希望这可以帮到你!


1
不错的想法。我在想是否可以将其包装在一个单一的中间件中,手动调用静态中间件,以便记录器函数可以访问 req:https://gist.github.com/robertklep/a84cfd344d69348d4bd699339f200c6e - robertklep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接