user3612986
user3612986

Reputation: 325

Capture all http requests with node/express

I am looking to capture all of the data from any request (images, fonts, css, js, etc) on my website so that I can capture the file details, specifically the file name and file size. I have found almost an identical question/solution:

Node.js : How to do something on all HTTP requests in Express?

But the solution appears to be deprecated with Express v4. Is there a simple solution to do this? As another approach I have tried the below solution with no luck:

var express = require("express");
var path = require("path");
var port = process.env.PORT || 3000;

var app = express();
var publicPath = path.resolve(__dirname, "public");

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

app.get("/", function(req, res){
    // I want to listen to all requests coming from index.html
    res.send("index.html");
});

app.all("*", function(){
    // can't get requests
})

app.listen(port, function(){
    console.log(`server listening on port ${port}`);
});

Also I am not looking to do this from Fiddler/Charles because I am looking to display this data on my site.

Upvotes: 2

Views: 3598

Answers (1)

Seth
Seth

Reputation: 10454

Express routes are predicated on order. Notice the answer that you linked in your question has the middleware defined, and used before all other routes.

Secondly you're trying to implement something that requires middleware, not a wildcard route. The pattern in link you provided in your question is not deprecated according to their docs.

app.use(function (req, res, next) {
  // do something with the request
  req.foo = 'testing'
  next(); // MUST call this or the routes will not be hit
});

app.get('/', function(req, res){
    if (req.foo === 'testing') {
      console.log('works');
    }

    res.send("index.html");
});

Upvotes: 2

Related Questions