Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
17
rated 0 times [  23] [ 6]  / answers: 1 / hits: 41019  / 7 Years ago, sun, august 6, 2017, 12:00:00

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?


More From » express

 Answers
3

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);

[#56854] Thursday, August 3, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deniseryannd

Total Points: 169
Total Questions: 85
Total Answers: 96

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;