Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js not showing console.log message when routing

Note: I am very new to express

var express = require('express');
var app = express();

app.get('/', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
var things = require('./things/things.js');

//both index.js and things.js should be in same directory
app.use('/things', things);
//Simple request time logger
app.use('/',function(req, res, next){
   console.log("A new request received at " + Date.now());

   //This function call is very important. It tells that more processing is
   //required for the current request and is in the next middleware
   //function/route handler.
   next();
});

app.listen(3000);

I am learning about middleware functions and am trying to show a console.log message when I go to localhost:3000, but nothing shows up in my console, what am I missing here?

like image 826
Snorlax Avatar asked Aug 06 '17 05:08

Snorlax


1 Answers

The problem is that Express passes requests to both middleware and route handlers in order of their declaration. If any of them are able to handle the request (by sending back a response), any other matching middleware or route handlers that got declared later won't get called.

That's what's happening in your situation, where your middleware is declared after the route handlers.

Try moving your middleware to the front:

app.use('/',function(req, res, next){
   console.log("A new request received at " + Date.now());
   next();
});

app.get('/', function(req, res) {
   res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});

var things = require('./things/things.js');

app.use('/things', things);
like image 161
robertklep Avatar answered Sep 18 '22 15:09

robertklep