node.js表示变量undefined?

时间:2014-06-15 02:48:58

标签: node.js express

我正在尝试这一行

router.post('/ login',passport.authenticate ...)

路由器位于我目录的路由器文件夹中。我已将其导出为模块,并在我的app.js文件中使用它。

在app.js中,我按此顺序有我的要求:

var passport = require('passport');
var routes = require('./routes/index');
var users = require('./routes/users');
var User = require('./models/models.js')

所以路线不应该能够访问护照吗?

这是我的路线/索引

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

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

router.post('/login', passport.authenticate('local', {
    successRedirect: '/home',
    failureRedirect: '/login',
    failureFlash: true
}));

router.get('/login', function(req, res, next) {
    var errors = req.flash('error');
})
module.exports = router;

这是我app.js的开头

var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var routes = require('./routes/index');
var users = require('./routes/users');
var User = require('./models/models.js');
var PassportLocalStrategy = require('passport-local');

2 个答案:

答案 0 :(得分:0)

需要在模块内重新包含护照作为变量。

答案 1 :(得分:0)

var passport = require('passport');文件的顶部添加routes/index.js

,将您的路由器包裹在module.exports = function(passport) {};中,并将passport传递到routes中的app.js要求。

像这样:var routes = require('./routes/index')(passport);