Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 613
Adam Halasz Avatar asked Aug 31 '11 21:08

Adam Halasz


People also ask

How does node js handle multiple HTTP requests?

How NodeJS handle multiple client requests? NodeJS receives multiple client requests and places them into EventQueue. NodeJS is built with the concept of event-driven architecture. NodeJS has its own EventLoop which is an infinite loop that receives requests and processes them.

Can Express handle multiple requests?

Express. js use different kinds of middleware functions in order to complete the different requests made by the client for e.g. client can make get, put, post, and delete requests these requests can easily handle by these middleware functions.

How many HTTP requests can node js handle?

As is, node. js can process upwards of 1000 requests per second and speed limited only to the speed of your network card. Note that it's 1000 requests per second not clients connected simultaneously. It can handle the 10000 simultaneous clients without issue.

Do node JS servers block on HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.


1 Answers

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)

like image 127
Rahman Kalfane Avatar answered Sep 22 '22 05:09

Rahman Kalfane