Home > Net >  new TypeError('Router.use() requires a middleware function but got a ' gettype(fn))
new TypeError('Router.use() requires a middleware function but got a ' gettype(fn))

Time:09-27

I have tried to run this code:

const connectToMongo = require('./db')
const express = require('express')
connectToMongo();
const app = express()
const port = 3000
// Available Routes
app.use('/api/auth', require('./routes/auth'))
app.use('/api/notes', require('./routes/notes'))



app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

But it is giving me this error:

C:\Users\CC\Desktop\Mern course\inotebook\inotebook\Backend\node_modules\express\lib\router\index.js:469
      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:\Users\CC\Desktop\Mern course\inotebook\inotebook\Backend\node_modules\express\lib\router\index.js:469:13)
    at Function.<anonymous> (C:\Users\CC\Desktop\Mern course\inotebook\inotebook\Backend\node_modules\express\lib\application.js:227:21)
    at Array.forEach (<anonymous>)
    at Function.use (C:\Users\CC\Desktop\Mern course\inotebook\inotebook\Backend\node_modules\express\lib\application.js:224:7)
    at Object.<anonymous> (C:\Users\CC\Desktop\Mern course\inotebook\inotebook\Backend\index.js:7:5)      
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
[nodemon] app crashed - waiting for file changes before starting...

I can't find the problem! I am learning so please give a beginner-friendly answer

CodePudding user response:

I have found the answer there was a problem in auth.js

CodePudding user response:

you should be passing a function which accepts req, res and a callback to the router.

here is the example. please ensure that ./routes/auth and ./routes/notes are a middleware function.

enter image description here

  • Related