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:\Users\decopiapo\restserver1221\node_modules\express\lib\router\index.js:458:13) at Function. (C:\Users\decopiapo\restserver1221\node_modules\express\lib\application.js:220:21) at Array.forEach () at Function.use (C:\Users\decopiapo\restserver1221\node_modules\express\lib\application.js:217:7) at Server.routes (C:\Users\decopiapo\restserver1221\models\server.js:58:14) at new Server (C:\Users\decopiapo\restserver1221\models\server.js:19:14) at Object. (C:\Users\decopiapo\restserver1221\app.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
You can export is as you like, the problem is how you require it.
Check your server file, if you export it like this:
// router
module.exports = {myRouter, myvar};
then you need to require it like this:
// app
app.use('/', routerFile.myRouter);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.