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

标签 node.js http express

我提供静态文件使用:

app.use(express.static('static'));

我在 ./static/ 下有一个 index.html 和一堆其他文件,这些文件显示在 http://localhost:8080 上。

有什么方法可以拦截 GET 请求并确定用户何时打开了静态文件?我试过了

app.get('/', (req, res) => { console.log("Opened!") }

但这行不通。

最佳答案

编辑:感谢@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);

因为任何明确的请求最多只能由一个中间件完成,所以在静态中间件之前监听“请求已结束”事件,并在我们确定静态中间件已经结束后将其分离满足要求就足够了。希望这对您有所帮助!

关于node.js - 检查用户是否在 Express 中打开了静态文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53558195/

相关文章:

mysql - 获取 ECONNREFUSED 127.0.0.1 :3306 error while conencting toa MySQL db using Node. js

php - 在没有API的情况下如何测试客户端?

python - HTTP 错误 403 : Forbidden urlib2 Python 2. 7

javascript - Expressjs 使用route.render 传递本地变量

javascript - 从 Sequelize getter 方法访问关联表

node.js - `npm start` : ERROR watch EMFILE although open files limit = 65536 问题

node.js - 蒙哥错误: selector must be a valid JavaScript object

node.js - Angular 和NPM问题

node.js - 无法关闭函数调用

javascript - 匹配 Express 中除 '/' 之外的所有路由