Search code examples
node.jsexpressmiddlewareexpress-jwt

Using Middle ware cause 404 in Express


I'm using express.js with express router. My files look like this:

./Routers -> api.js

./controllers -> ApiController.js

inside api.js I send the request to the ApiController. It looks like this:

router.get('/',ApiController.home)

and inside controller it looks like this:

exports.home = (req,res,next)=>{res.send('hello') }

I have a middleware like this:

function authenticate(req, res, next) {
    //Some functions here
      next()
    })
  }

If I change my controller and add the middleware like this:

exports.home = authenticate ,(req,res)=>{res.send('hello') }

I'll get 404. Any Idea whats wrong with it?


Solution

  • You want to add the middleware when declaring the get router

     router.get('/', authenticate, ApiController.home)
    

    If you do what you're doing

     exports.home = authenticate ,(req,res)=>{res.send('hello') }
    

    This is basically saying that exports.home = authenticate and ignores your function that has the res.send. Therefore when you hit exports.home function it will only have a next() and not res.send to client. The next will just make the request pass through and it will hit the last error handler which is returning you a 404 as there was never a response received.