There have been some middleware changes on the new version of express and I have made some changes in my code around some of the other posts on this issue but I can\'t get a
check your routes.js file
example my routes.js
const express = require('express')
const router = express.Router()
const usersController = require('../app/controllers/usersController')
const autheticateuser = require('../app/middlewares/authentication')
router.post('/users/login', autheticateuser, usersController.login)
router.post('/users/register', autheticateuser, usersController.register)
check end of routes.js
module.exports = router
if not there add and module.exports = router run again
If your Error is : "TypeError: Route.post() or Route.get() requires middleware function but got a Object"
goto controller.js (i.e., usersController) and check all the function names you might misspelled , or you given in function routes file but missed in contollers
const User = require('../models/user')
const express = require('express')
const router = express.Router()
module.exports.register = (req, res) => {
const data = req.body
const user = new User(data)
user.save()
.then((user) => {
res.send(user)
})
.catch((err) => {
res.json(err)
})
}
in routes.js i given two routes but in controllers i missed to define route for
router.post('/users/login')
this will make error **
"TypeError: route.post() requires middleware function but got a Object"
**
In my case i wasn't exporting the module.
module.exports = router;
Simple solution if your are using express and doing
const router = express.Router();
make sure to
module.exports = router ;
at the end of your page
I had this error and solution help which was posted by Anirudh. I built a template for express routing and forgot about this nuance - glad it was an easy fix.
I wanted to give a little clarification to his answer on where to put this code by explaining my file structure.
My typical file structure is as follows:
/lib
/routes
---index.js
(controls the main navigation)
/page-one
/page-two
---index.js
(each file [in my case the index.js within page-two, although page-one would have an index.js too]- for each page - that uses app.METHOD
or router.METHOD
needs to have module.exports = router;
at the end)
If someone wants I will post a link to github template that implements express routing using best practices. let me know
Thanks Anirudh!!! for the great answer.
Check your all these file:
var users = require('./routes/users');
var Users = require('./models/user');
var Items = require('./models/item');
Save properly, In my case, one file was missed and throwing the same error
If your are using express above 2.x
, you have to declare app.router
like below code. Please try to replace your code
app.use('/', routes);
with
app.use(app.router);
routes.initialize(app);
Please click here to get more details about app.router
app.router
is depreciated in express 3.0+
. If you are using express 3.0+, refer to Anirudh's answer below.