1

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?

5
  • 2
    Post your index and users routes Commented Oct 9, 2015 at 7:44
  • U mean the code inside routes/index.js and routes/users.js file? Commented Oct 9, 2015 at 7:46
  • Yes, because that's where the problem probably is Commented Oct 9, 2015 at 7:48
  • i have updated the question. Commented Oct 9, 2015 at 8:40
  • Your index.js is not correct at all. It should look like your user.js Commented Oct 9, 2015 at 8:41

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

12 Comments

let me make it a bit more clear, I have referenced this article (ibm.com/developerworks/library/wa-nodejs-polling-app) and copied the code, and it say to inject THAT code in my index.js, But it doesn't seem to work.
please, refer 'Listing 13' at the link i provided.
If you've read correctly they're using routes.js like this in app.js app.get('/polls/polls', routes.list);
Fix your index.js according to my answer and it will work
What should be the code in /*list implementation */ ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.