Search code examples
node.jstypescriptexpressloggingmiddleware

Middleware Not Working Due to File Structure


I am following a tutorial on middleware and I have created the middleware that logs the url visited to the console. When I created 2 endpoints in the same file and used the middleware, it logged the url visited to the console as expected. I decided to a file for each endpoint and the middleware doesn't work. I think this might be due to the file structure. My background is in Java but dabbling into Typescript. The message that are meant to be displayed in the browser are not getting displayed also. My goal is to get the message displayed to the browser and the url visited displayed to the console.

index.ts

import express from 'express';
import logger from './utilities/logger';
import route from './routes/index'

const app = express();
const port = 3002;

app.use('/sport', route)

// start the Express server
app.listen(port, () => {
  console.log(`server started at http://localhost:${port}`);
});

logger.ts

import express from 'express';

const logger = (req: express.Request, res: express.Response, next: Function): 
void => {
    const url = req.url;
    console.log(`${url} was visited - hello`);
    // next();
}

export default logger;

routes/index.ts

import express from 'express';
import football from './api/football'
import basketball from './api/basketball'
import skiing from './api/skiing'

const route = express.Router();

route.get('/', (_req, _res) => {
    _res.send("Main route file");
});

route.use('/basketball', basketball);
route.use('/football', football);
route.use('/skiing', skiing);

export default route;

basketball.ts

import express from 'express';
import logger from '../../utilities/logger';

const route = express.Router();

route.get('/', logger,(_req, _res) => {
    _res.send('bball!');
});

export default route;

football.ts

import express from 'express';
import logger from '../../utilities/logger';

const route = express.Router();

route.get('/', logger,(_req, _res) => {
    _res.send('footie!');
});

export default route;

file structure

enter image description here

console output

enter image description here


Solution

  • The Expressjs documentation doesn’t even document the Request.url property of a Request. Very clearly in the documentation they state that:

    Request.url is not a native Express property, it is inherited from Node’s http module.

    It is unclear why you logged Request.url. Request.originalUrl is much like Request.url; however, it retains the original request URL. This is what you need. It is available both in middleware and router objects.

    const logger = (req: express.Request, res: express.Response, next: Function): void => {
        const url = req.originalUrl;
        /* •••Rest of code••• */
    }