hi, i’m writing a application under NodeJS but got the following error:
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:Usersdecopiaporestserver1221node_modulesexpresslibrouterindex.js:458:13)
at Function. (C:Usersdecopiaporestserver1221node_modulesexpresslibapplication.js:220:21)
at Array.forEach ()
at Function.use (C:Usersdecopiaporestserver1221node_modulesexpresslibapplication.js:217:7)
at Server.routes (C:Usersdecopiaporestserver1221modelsserver.js:58:14)
at new Server (C:Usersdecopiaporestserver1221modelsserver.js:19:14)
at Object. (C:Usersdecopiaporestserver1221app.js:3:16)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
[nodemon] app crashed – waiting for file changes before starting…
The Code is:
const {Router} = require(‘express’);
const { check } = require(‘express-validator’);
const { login} = require(‘../controllers/auth’);
const { validatefields } = require(‘../middlewares/validate-fields’);
const router = Router();
router.post(‘/login’, [
check(’email’, ‘Email is mandatory’).isEmail(),
check(‘password’, ‘The Password is mandatory’).not().isEmpty(),
validatefields
],
login);
module.exports = {
router
}
….
note
If i change “module.exports = { router }” for “module.exports = router” the problem disappears, but what if i want to export a constant or other function?
example:
const {Router} = require(‘express’);
const { check } = require(‘express-validator’);
const { login} = require(‘../controllers/auth’);
const { validatefields } = require(‘../middlewares/validate-fields’);
const myvar = ‘12321@as’;
const router = Router();
router.post(‘/login’, [
check(’email’, ‘Email is mandatory’).isEmail(),
check(‘password’, ‘The Password is mandatory’).not().isEmpty(),
validatefields
],
login);
module.exports = {
router,
myvar
}
the error appears again…
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
How i can solve this problem. Any Ideas?
Node Version: v16.11.1 –
Express Version : 4.17.1