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:UsersCCDesktopMern courseinotebookinotebookBackendnode_modulesexpresslibrouterindex.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:UsersCCDesktopMern courseinotebookinotebookBackendnode_modulesexpresslibrouterindex.js:469:13)
at Function.<anonymous> (C:UsersCCDesktopMern courseinotebookinotebookBackendnode_modulesexpresslibapplication.js:227:21)
at Array.forEach (<anonymous>)
at Function.use (C:UsersCCDesktopMern courseinotebookinotebookBackendnode_modulesexpresslibapplication.js:224:7)
at Object.<anonymous> (C:UsersCCDesktopMern courseinotebookinotebookBackendindex.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
2
Answers
I have found the answer there was a problem in auth.js
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.