Express Js:Router.use()需要中间件功能

时间:2015-10-09 07:42:54

标签: javascript node.js express

我正在Express Js中开发一个应用程序。当我尝试运行应用程序时,我收到此错误:

enter image description here

我的app.js文件是这样的:

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;

我的index.js是这样的:

    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;

user.js就是这样:

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;

我试图在SO找到我的解决方案,但不能。如果我需要提供任何其他文件,请随时告诉我。有什么帮助吗?

1 个答案:

答案 0 :(得分:2)

您应该像Dir:\>tnsping <your service_name> [enter] 中一样在index.js中定义路线。

代码中的

user.js期望app.use('/', routes)成为routes的实例,但是您要导出一个带有函数的对象而不是它。

因此,您的Router文件应具有以下结构:

index.js