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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With