Javascript Express Js:Router.use()需要中间件函数

Javascript Express Js:Router.use()需要中间件函数,javascript,node.js,express,Javascript,Node.js,Express,我正在用ExpressJS开发一个应用程序。当我尝试运行应用程序时,出现以下错误: 我的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

我正在用ExpressJS开发一个应用程序。当我尝试运行应用程序时,出现以下错误:

我的
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;
    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;
我的
index.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;
    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;

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

您应该像在
user.js
中一样,在
index.js
中定义路由

app.use(“/”,routes)
在您的代码中,预期
routes
路由器的实例,但您导出的是具有函数的对象,而不是该对象

因此,您的
index.js
文件应具有以下结构:

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;

发布你的索引和用户路径你的意思是
routes/index.js
routes/users.js
文件中的代码?是的,因为这就是问题所在,我可能已经更新了问题。你的
index.js
根本不正确。它应该看起来像你的
user.js
让我说得更清楚一点,我引用了这篇文章()并复制了代码,它说要在我的index.js中插入代码,但它似乎不起作用。请,请参阅我提供的链接中的“清单13”。如果您阅读正确,他们在
app.js
app.get('/polls/polls',routes.list)中使用的是
routes.js
根据我的答案修复你的
index.js
,它会起作用
/*列表实现中的代码应该是什么*/