Saani
Saani

Reputation: 782

Express Js: Router.use() Requires Middleware function

I am developing an application in Express Js. When I try to run the application I get this error:

enter image description here

My app.js file is like this:

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();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
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
    });
  });
}
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
module.exports = router;

My index.js is like this:

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

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

router.get("/list", function (req, res, next) {
    Poll.find({}, 'question', function (error, polls) {
        res.json(polls);
    });
});

router.get("/poll", function (req, res, next) {
    var pollId = req.params.id;

    // Find the poll by its ID, use lean as we won't be changing it
    Poll.findById(pollId, '', {lean: true}, function (err, poll) {
        if (poll) {
            var userVoted = false,
                    userChoice,
                    totalVotes = 0;

            // Loop through poll choices to determine if user has voted
            // on this poll, and if so, what they selected
            for (c in poll.choices) {
                var choice = poll.choices[c];

                for (v in choice.votes) {
                    var vote = choice.votes[v];
                    totalVotes++;

                    if (vote.ip === (req.header('x-forwarded-for') || req.ip)) {
                        userVoted = true;
                        userChoice = {_id: choice._id, text: choice.text};
                    }
                }
            }

            // Attach info about user's past voting on this poll
            poll.userVoted = userVoted;
            poll.userChoice = userChoice;

            poll.totalVotes = totalVotes;

            res.json(poll);
        } else {
            res.json({error: true});
        }
    });
});

router.get("/create", function (req, res, next) {
    var reqBody = req.body,
            // Filter out choices with empty text
            choices = reqBody.choices.filter(function (v) {
                return v.text != '';
            }),
            // Build up poll object to save
            pollObj = {question: reqBody.question, choices: choices};

    // Create poll model from built up poll object
    var poll = new Poll(pollObj);

    // Save poll to DB
    poll.save(function (err, doc) {
        if (err || !doc) {
            throw 'Error';
        } else {
            res.json(doc);
        }
    });
});

module.exports = router;

And user.js is this:

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

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

module.exports = router;

I tried to find my solution on SO, but couldn't. Feel free to tell me if i need to provide any other file. Any help?

Upvotes: 1

Views: 816

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

You should define routes in your index.js like you do in user.js.

app.use('/', routes) in your code expects routes to be an instance of a Router, but you're exporting an object with functions instead of that.

So your index.js file should have the following structure:

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

router.get("/", function (req, res) {
    res.render('index');
});

router.get("/list", function(req, res) {/*list implementation*/});

....

module.exports = router;

Upvotes: 2

Related Questions