4

I know there are lot of questions in SO but none of them gave me a solution

routes/authentication/index.js

import { Router } from 'express'

const router = Router();

router.get('/', (_req, _res) => console.log("Works"))

// module.exports = router                    <-- this works
export default router                      // <-- this doesn't

constants.js

const ROUTES = {
    'AUTHENTICATION' : require('../routes/authentication')
}

export default ROUTES

and using it in app.js as

import express from 'express'
import connectDatabase from './connectDb';
import ROUTES from './constants';
const app = express();

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}
connectDatabase()

app.get('/', (_req, res) => {
  res.send("hello world")
})

app.use('/auth', ROUTES.AUTHENTICATION)

export default app;

Now with module.exports = router works but export default router throws an error

TypeError: Router.use() requires a middleware function but got a Object

I tried finding the cause for the problem but couldn't. Thanks in advance

Ashutosh patole
  • 336
  • 3
  • 13

1 Answers1

1

You require the router file in constants.js, hence module.exports works.

For export default router to work, you need to import it.

Vishnudev
  • 7,765
  • 1
  • 11
  • 43