1

I want to broke down my routers into separate file rather than keeping all API routes in a single file. So i tried to identify user URL using a middle ware and call the api according to the url as you seeing bellow but middleware function is not working . how to solve this?

//HERE IS INDEX.jS file CODE

const express = require("express");
const dotenv = require("dotenv");

const app = express();

const PORT = process.env.PORT || 7000;
app.listen(PORT);

app.use("/users", require("./routes/users/users"));

//==========================================================

//HERE IS users.js FILE CODE

const express = require("express");`enter code here`
const router = require("express").Router();


express().use(selectApi);

  function selectApi(req, res, next) {

console.log("this line also not executing") 


  switch(req.originalUrl){
      case '/':
          // calling api here from a nother separate file

      case '/user/:id'
         // calling api here from a nother separate file
  }
}



module.exports = router;

1 Answers1

2

There is an example in the Express.js Routing Guide. I've modified it slightly to fit your example.

users.js

var express = require('express')
var router = express.Router()

// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
  console.log('Time: ', Date.now())
  next()
})
// define the home page route
router.get('/', function (req, res) {
  // calling api here from a nother separate file
})

router.get('/user/:id', function (req, res) {
  // calling api here from a nother separate file
})

module.exports = router

index.js

const express = require("express");
const dotenv = require("dotenv");

const app = express();

const PORT = process.env.PORT || 7000;
app.listen(PORT);

app.use("/users", require("./routes/users/users"));

Alan Friedman
  • 1,582
  • 9
  • 7