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

3
  • 1
    This shlould works, show us the routes files. Do you export it properly? Commented Aug 17, 2018 at 19:06
  • can we see the exports of './routes/api' and './routes/leads'? Just the export contents, not the entire file. Commented Aug 17, 2018 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 Commented Aug 17, 2018 at 19:15

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.