2019-09-11
Getting TypeError: Router.use() requires a middleware function but got a undefined
stackoverflow
Question

I am getting this error for my below code when I start my server. What is wrong in this code?

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
      ^

TypeError: Router.use() requires a middleware function but got a undefined

shop.js:

const path = require('path')
const express = require('express');

const rootDir = require('../util/path');
const adminData = require('./admin');

const router = express.Router();

router.get('/', (req, res, next) => {
    const products = adminData.products;
    res.render('shop', {
        prods: products,
        docTitle: 'Shop'
    });
});

admin.js

module.exports = router;

const path = require('path');
const express = require('express');

const rootDir = require('../util/path');

const router = express.Router();

const products = [];

// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
    res.sendFile(path.join(rootDir, 'views', 'add-product.html'));
});

// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
    products.push({
        title: req.body.title
    });
    res.redirect('/');
});

module.exports = router;
module.exports = products;

app.js:

 const path = require('path');
 const express = require('express');
 const bodyParser = require('body-parser');

 const app = express();

 app.set('view engine', 'pug');
 app.set('views', 'views');

 const adminData = require('./routes/admin');
 const shopRoutes = require('./routes/shop');

 app.use(bodyParser.urlencoded({
     extended: false
 }));

 app.use(express.static(path.join(__dirname, 'public')));

 app.use('/admin', adminData.routes);
 app.use(shopRoutes);

 app.use((req, res, next) => {
     res.status(404).sendFile(path.join(__dirname, 'views', '404.html'));
 });

 app.listen(3000, () => {
     console.log('Server started!!');
 });
Answer
1

Looks like your exported object is being overwritten here

module.exports = router;
module.exports = products;

Essentially, you are exporting only products object. Try

module.exports = { router, products };

and

app.use('/admin', adminData.router);
Getting TypeError: Router.use() requires a middleware function but got a undefined
See more ...