Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 404 Vote(s) - 3.47 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Express error - TypeError: Router.use() requires middleware function but got a Object

#1
I am getting this error when I run npm start to run my express app.

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

my **app.js** code

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

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

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);



/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});

module.exports = app;

my **index.js** code

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});

/* GET Hello World page. */
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!' })
});

module.exports = router;


I am quirte new to using Node and express. I cant see where I have gone wrong. Can anybody see what my problem is?

Reply

#2
I fixed it by removing the `app.use(/users, users);`

I don't need this at the minute so maybe that is why it started breaking.
Reply

#3
I found the answer in the comments from [Kop4lyf][1]:

> check your users.js. It should also be exporting the router like
> index.js, if you can try that.

However, this question was my top search result when I ran into this issue, so I am promoting to an answer.

-------

The error is caused because one of your route modules is not being exported - meaning Express does not have access to it when it tries to identify all of your routes.

You can fix this by adding `module.exports = router;` to the end of each of your route files.

Example:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
//Do whatever...
});

module.exports = router;

More information about `module.exports` can be found on [this question][2] or the [offcial Node.js documentation][3].

[1]:

[To see links please register here]

[2]:

[To see links please register here]

[3]:

[To see links please register here]

Reply

#4
I have fixed this by adding which i am using somewhere. So please check your all exports.

module.exports = router;
Reply

#5
This error comes when you forgot to export the module which uses the Router.

Your mentioned code works perfectly with some tweaks.

if your app.js is main/starting point of the app.

it should have

const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

instead of

module.exports = app;

(optional)Generally index.js is used for starting point of app. Rename index.js as helloworld.js and change same at require statement

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

to

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


run this app using the following command

node app.js

Reply

#6
Your index.js file is fine you just have to create **users.js** and export it.

let express = require('express');
let router = express.Router();

//Login Page - GET REQUEST
router.get('/login',(req,res)=> {
res.send('login page');
})


//Register Page - GET REQUEST
router.get('/register',(req,res)=> {
res.send('register page');
});

module.exports = router;
Reply

#7
**If you have checked all the solution than also having this error than check this one**

Another cause of having this error is calling a method which is not exist or not not exported.
In my case i am calling **login** method but i forgot to define them

I was trying to call this method

app.post('/api/login', db.login);
but i had forgot to create login method so i got this error. also try to check spelling mistake may be you might have typed wrong spell
Reply

#8
I had the same problem, and then I discovered that I was missing this line in one of my controllers !

`return api;` //it might be `return router`for your code !

I added this line to my code and it worked fine.
Reply

#9
in every module **export the router** and **keep one handler for the default
path '/'**

// in index.js
const authRoute = require("./routes/authRoute");

app.use("/auth", authRoute);


// in authRoute.js

const express = require("express");
const router = express.Router();
router.get("/", (req, res) => {
// code
});

module.exports = router;
Reply

#10
I found it after lot of struggle! as everything syntactically correct, nothing wrong with code that was written, it was due to the code that was not written yet! This could happen if you have implemented index.js but not yet users.js. However, you have already defined both lines
app.use('/', routes);
app.use('/users', users);
If you are eager to test index.js right away without waiting for users.js to be implemented. That's exactly when it errors out.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through