2

I am trying to put my routes into multiple files to organize based on module. if i only use one file like this all works fine

const apiRoutes = require('./routes/api')
app.use('/api', apiRoutes);

but when i use the below code in my index.js and register 2 files

const apiRoutes = require('./routes/api')
const apiRoutes2 = require('./routes/leads')
app.use(express.json());
app.use('/api', apiRoutes);
app.use('/leads', apiRoutes2);

i get this error

C:\nodeRoot\node_modules\express\lib\router\index.js:458
  throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
  ^

TypeError: Router.use() requires a middleware function but got a Object
at Function.use (C:\nodeRoot\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (C:\nodeRoot\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)

So not sure if you can only register 1 file for routes or what else is causing this issue

MisterniceGuy
  • 1,646
  • 2
  • 18
  • 41
  • 1
    This shlould works, show us the routes files. Do you export it properly? – BrTkCa Aug 17 '18 at 19:06
  • can we see the exports of `'./routes/api'` and `'./routes/leads'`? Just the export contents, not the entire file. – Jorge Fuentes González Aug 17 '18 at 19:13
  • That was exactly my problem, when i copied the first file to create a second route i forgot the export at the end. Once i added all worked like a charm so it had nothing to do with json or bodyparser but the missing export statement in the second route file – MisterniceGuy Aug 17 '18 at 19:15

1 Answers1

2

I got similar error few days ago, and I forgot to export my router from one of my routes.
Make sure that you are exporting your router from your second routes files.

module.exports = router;
dAxx_
  • 2,210
  • 1
  • 18
  • 23