Node js Next不是护照策略错误中的函数

时间:2019-03-15 17:24:48

标签: javascript node.js express passport.js passport-local

似乎无法使登录系统正常工作。我正在使用带有用户信息的json文件,并正在使用node.js,express和通行证。这是我的代码(删节后仅包含相关信息)。

Index.js

const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 5000
const myDB = require('./jDB');
const passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
const app = express();
const bodyParser = require('body-parser');

app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(passport.initialize());
app.use(passport.session());

app.get('/success', (req, res) => res.send("Welcome "+req.query.username+"!!"));
app.get('/error', (req, res) => res.send("error logging in"));

passport.serializeUser(function(user, cb) {
  cb(null, user.id);
});

passport.deserializeUser(function(id, cb) {
  User.findById(id, function(err, user) {
    cb(err, user);
  });
});

passport.use(new LocalStrategy({

  usernameField: 'username',
  passwordfield : 'password'

},
  function(username, password, done) {
  console.log('I was given ' + username + " and " + password);
  if(myDB.login(username, password)) {
      console.log('Logged in');
      return done(null, user); 
  } else {
      console.log('Failed login');
      return done(null, false);
  }
}));


function myAuth(req, res) {
  passport.authenticate('local', { 
    successRedirect: '/success', 
    failureRedirect: '/error', 
  })(req, res);


}

app.get('/login', (req, res) => res.render('pages/login', { root : __dirname}));

app.post('/login', (req, res) => myAuth(req, res));

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));  

jDB.js

const login = require('./json/users.json');

module.exports = {
    login : function(mUser, mPass) {
        var cryptPass = crypto.createHmac('sha256', mPass).digest('hex');
        for(var exUser in login) {
            console.log(json.stringify(login[exUser]) + " against " + mUser);
            if(login[exUser].username == mUser && login[exUser].password == cryptPass) {
                return true;
            }
        } 
        return false;

    }

login.ejs的表单部分:

<form action='/login' method='post'>
            <div class="form-group">
              <label for="username">Username</label>
              <input type="text" class="form-control" name="username">
            </div>
            <div class="form-group">
              <label for="pasword">Password</label>
              <input type="password" class="form-control" name="password">
            </div>
            <button type="submit" class="btn btn-primary">Login</button>
          </form>

每当我尝试使用正确的用户名和密码详细信息登录时,都会出现以下错误:

TypeError: next is not a function
    at Strategy.strategy.error (/home/tommy/carrers-week/node_modules/passport/lib/middleware/authenticate.js:356:9)
    at Strategy.authenticate (/home/tommy/carrers-week/node_modules/passport-local/lib/strategy.js:93:17)
    at attempt (/home/tommy/carrers-week/node_modules/passport/lib/middleware/authenticate.js:361:16)
    at authenticate (/home/tommy/carrers-week/node_modules/passport/lib/middleware/authenticate.js:362:7)
    at myAuth (/home/tommy/carrers-week/index.js:195:5)
    at app.post (/home/tommy/carrers-week/index.js:202:34)
    at Layer.handle [as handle_request] (/home/tommy/carrers-week/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/tommy/carrers-week/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/tommy/carrers-week/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/tommy/carrers-week/node_modules/express/lib/router/layer.js:95:5)

我真的不知道如何解决此问题,因此在此先感谢您的所有帮助!

1 个答案:

答案 0 :(得分:1)

从错误跟踪中可以看到该应用程序在

中引发
passport.authenticate

此外,它为next方法感到悲伤。 我要做的一件事是在

范围内进行此调用
function next() {
  console.log(arguments)
}

或只提供它:

function myAuth(req, res, next) {
  passport.authenticate('local', { 
    successRedirect: '/success', 
    failureRedirect: '/error', 
  })(req, res, next);


}

app.post('/login', (req, res, next) => myAuth(req, res, next));

要获得更多见识,可以看看

  

passport-local / blob / master / lib / strategy.js:93

try {
    if (self._passReqToCallback) {
      this._verify(req, username, password, verified);
    } else {
      this._verify(username, password, verified);
    }
  } catch (ex) {
    return self.error(ex); //93
  }
  

passport / blob / master / lib / middleware / authenticate.js:356

  strategy.error = function(err) {
    if (callback) {
      return callback(err);
    }

    next(err); //356
  };

等等,

没有提供给本地策略的回调将触发next()调用