0

how u doing?

Here is my code:

const router = Router();

router.use(
    `${routePrefix}/v1/associate-auth/`,
    associateAuthRoutesV1(router)
  );
  router.use(
    `${routePrefix}/v1/associate/`,
    JWTVerify,
    associateRoutesV1(router)
  );
app.use('/', router);

Here is an exemple of my routes content:

  router.post('/', async (_req, res) => {
    res.send('OK');
  });

The problem is: When I don't set the root('/') in one of routes file, Express find the next file with the same method in root ('/').

How can I configure to return 404 when there is no route specify?

1 Answers1

0

use http-errors module and create 2 middlewares, the first for error handler, and the second for endpoint handler :

error handler in errorHandler.js

function checkError (err,req,res,next) => {
  return res.status(err.status || 500).json({
    code: err.status || 500,
    status: false,
    message: err.message
  })
}

module.exports = checkError

endpoint handler in endpointHandler.js

// endpoint handler in endpointHandler.js
const isError = require('http-errors')

function checkRoute(req,res,next) +> {
  return next(isError.NotFound('invalid endpoint')
}

module.exports = checkRoute

then in your main js :

const app = require('express')

const checkError = require('./errorHandler.js')

const checkRoute = require ('./endpointHandler.js')

const router = Router();

router.use(
    `${routePrefix}/v1/associate-auth/`,
    associateAuthRoutesV1(router)
  );
  router.use(
    `${routePrefix}/v1/associate/`,
    JWTVerify,
    associateRoutesV1(router)
  );
app.use('/', checkRoute, router);

app.use(checkError)
Mudzia Hutama
  • 414
  • 3
  • 8