"Throw new typeerror('router.use() requires a middleware function but got a ' + gettype(fn))" (Code Answer's)
We have a very easy explanation of the problem. When you make an API using node, express, and MySQL, suddenly you receive an error that is:
throw new TypeError(‘Router.use() requires a middleware function but got a ‘ + gettype(fn))
The first mistake that you are making is using app.use() rather than app.set(). You are entering a string or any number to app.use() and looking for middleware function reference that's why the error is coming.
The second mistake you are making is overloading app.use().
TypeError: Router.use() requires a middleware function but got a Object
module.exports = router;
TypeError: app.use() requires a middleware function
const express = require('express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// tells express which template engine to use
app.set('view engine', 'pug');
const routes = require('./routes');
app.use(routes);
app.use((req, res, next) => {
console.log('Hello');
next();
});
app.use((req, res, next) => {
console.log("World");
next();
});
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error');
});
app.listen(3000, () => {
console.log('The application is running on localhost 3000');
});
You may also solve your problem by adding modules exports router; at the last end of every route file. That error may occur when route modules are not entered which are used by the routers. It means you have not allowed express to recognize all routes