我提供静态文件使用:
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/