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

42,903

Solution 1

Express is based on the Connect middleware.

The routing capabilities of Express are provided by the router of your app and you are free to add your own middlewares to your application.

var app = express.createServer();

// Your own super cool function
var logger = function(req, res, next) {
    console.log("GOT REQUEST !");
    next(); // Passing the request to the next handler in the stack.
}

app.configure(function(){
    app.use(logger); // Here you add your logger to the stack.
    app.use(app.router); // The Express routes handler.
});

app.get('/', function(req, res){
    res.send('Hello World');
});

app.listen(3000);

It's that simple.

(PS : If you just want some logging you might consider using the logger provided by Connect)

Solution 2

You should do this:

app.all("*", (req, res, next) => {
    console.log(req); // do anything you want here
    next();
});

Solution 3

You can achieve it by introducing a middleware function. app.use(your_function) can be of help. app.use with accept a function that will get executed on every request logged to your server. Example:

app.use((req, res, next) => {
    console.log("req received from client");
    next(); // this will invoke next middleware function
});

Solution 4

Express supports wildcards in route paths. So app.all('*', function(req, res) {}) is one way to go.

But that's just for route handlers. The difference is that an Express route handler is expected to send a response, and, if it doesn't, Express will never send a response. If you want to do something without explicitly sending a response, like check for a header, you should use Express middleware. app.use(function(req, res, next) { doStuff(); next(); }

Share:
42,903
Adam Halasz
Author by

Adam Halasz

Hi, I made 37 open source node.js projects with +147 million downloads. Created the backend system for Hungary's biggest humor network serving 4.5 million unique monthly visitors with a server cost less than $200/month. Successfully failed with several startups before I turned 20. Making money with tech since I'm 15. Wrote my first HTML page when I was 11. Hacked our first PC when I was 4. Lived in 7 countries in the last 4 years. aimform.com - My company adamhalasz.com - My personal website diet.js - Tiny, fast and modular node.js web framework

Updated on November 26, 2021

Comments

  • Adam Halasz
    Adam Halasz over 2 years

    So I would like to do something like:

    app.On_All_Incoming_Request(function(req, res){
        console.log('request received from a client.');
    });
    

    the current app.all() requires a path, and if I give for example this / then it only works when I'm on the homepage, so it's not really all..

    In plain node.js it is as simple as writing anything after we create the http server, and before we do the page routing.

    So how to do this with express, and what is the best way to do it?