Programmers learn & share
0 votes
563 views

Problem :

Facing following express issue
throw new typeerror('router.use() requires a middleware function but got a ' + gettype(fn))
by (6.9k points)   | 563 views

2 Answers

0 votes

Solution :

I had faced same issue in recent past.

After doing the research i found following solution to your issue:

If your are using express and your code is as below

const router = express.Router();

Then please make sure to update your code as below

module.exports = router;

And please do it at the end of your page

by (36.1k points)  
0 votes

This error occurs when your route modules are not being exported or you forget to export the modules which use the router. Means Express does not have access to it when tries to identify all of your routes.

Solutions:

Solution 1:

You can fix it by adding a module.exports = router; at the end of each your route files.

Example:

var express = require('express');

var router = express.Router();

router.get('/', function(req, res, next) {

     //Do whatever...

});

module.exports = router;

Solution 2:

If your app.js is the main starting point of the app, then it should have;

const port = process.env.PORT || 3000;

app.listen(port, () => console.log(`Listening on port ${port}...`));

instead of ;

modules exports = app;

Generally, index.js is used for the starting point of the app. Rename index.js as helloworld.js and change the same at the require statements;

var routes = require('./routes/index');

to

var routes = require('./routes/helloworld');

After doing all the changes run the following command

node app.js

Solution 3:

Another method of having this error is to call a method that does not exist or not exported. If you are calling the login method but forget to define them.

Example:

For example, you are calling the method

app.post( ‘/api/login’, db.login);

 

ago by (3.2k points)  
2,245 questions
2,807 answers
60 comments
241 users