Express.js& MySql:TypeError:undefined不是函数

时间:2015-03-24 04:45:20

标签: mysql node.js express sequelize.js

我正在尝试使用Sequelize ORM将Express.js与MySql一起使用来实现简单的登录功能。我在运行Express app时收到以下错误消息:

GET /signup [36m304 [90m16ms[0m
[90mPOST /signup [31m500 [90m15ms - 1.18kb[0m
TypeError: undefined is not a function
    at Strategy._verify (C:\Users\abhijeet.dhumal\workspace\Pentest\config\passport.js:46:14)
    at Strategy.authenticate (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport-local\lib\passport-local\strategy.js:87:10)
    at attempt (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport\lib\passport\middleware\authenticate.js:243:16)
    at Passport.authenticate (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport\lib\passport\middleware\authenticate.js:244:7)
    at next_layer (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\route.js:103:13)
    at Route.dispatch (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\route.js:107:5)
    at C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:195:24
    at Function.proto.process_params (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:251:12)
    at next (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:189:19)
    at next (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:166:38)

以下是我的代码段:

app.js

// app.js

var express  = require('express');
var app      = express();
var port     = process.env.PORT || 8080;
var passport = require('passport');
var flash    = require('connect-flash');
var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');
var session      = require('express-session');
var configDB = require('./config/database_mysql.js');
var Sequelize = require('sequelize')
, config    = require('./config/database_mysql.js')
, sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  port: config.port,
  logging: false
});

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.set('view engine', 'ejs'); // set up ejs for templating
app.use("/views/assets", express.static(__dirname + '/views/assets'));
app.use("/views/css", express.static(__dirname + '/views/css'));

require('./config/passport')(passport); // pass passport for configuration
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);

Passport.js

// config/passport.js

var LocalStrategy   = require('passport-local').Strategy;
var User            = require('../app/models/mysql_user');

module.exports = function(passport) {
    passport.serializeUser(function(user, done) {
        done(null, user.id);
    });

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

    passport.use('local-signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error
            if (err)
                return done(err);

            // check to see if theres already a user with that email
            if (user) {
                return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
            } else {

                // if there is no user with that email
                // create the user
                var newUser            = new User();

                // set the user's local credentials
                newUser.local.email    = email;
                newUser.local.password = newUser.generateHash(password); // use the generateHash function in our user model

                // save the user
                newUser.save(function(err) {
                    if (err)
                        throw err;
                    return done(null, newUser);
                });
            }
        });
    }));

    passport.use('local-login', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : 'email',
        passwordField : 'password',
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ 'local.email' :  email }, function(err, user) {
            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user)
                return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

            // if the user is found but the password is wrong
            if (!user.validPassword(password))
                return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata
            // all is well, return successful user
            return done(null, user);
        });
    }));
};

routes.js

app.get('/logout', function(req, res) {
        req.logout();
        res.redirect('/');
    });

    // signup
    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/profile',
        failureRedirect : '/signup',
        failureFlash : 'invalid username and password'
    }));

    // login
    app.post('/login', passport.authenticate('local-login', {
        successRedirect : '/profile',
        failureRedirect : '/login',
        failureFlash : 'invalid username and password'
    }));

database_mysql.js

module.exports = {
  username: 'root',
  password: 'root',
  database: 'sample',
  host    :  'localhost',
  port    : '3306'
};

登录形式:

    <form action="/login" method="post">
        <div class="form-group">
            <label>Email</label> <input type="text" class="form-control"
                name="email">
        </div>
        <div class="form-group">
            <label>Password</label> <input type="password" class="form-control"
                name="password">
        </div>

        <button type="submit" class="btn btn-default">Login</button>
    </form>

在我尝试注册或登录时的浏览器上,我收到以下错误消息:

TypeError: undefined is not a function at Strategy._verify (C:\Users\abhijeet.dhumal\workspace\Pentest\config\passport.js:46:14) at Strategy.authenticate (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport-local\lib\passport-local\strategy.js:87:10) at attempt (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport\lib\passport\middleware\authenticate.js:243:16) at Passport.authenticate (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\passport\lib\passport\middleware\authenticate.js:244:7) at next_layer (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\route.js:103:13) at Route.dispatch (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\route.js:107:5) at C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:195:24 at Function.proto.process_params (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:251:12) at next (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:189:19) at next (C:\Users\abhijeet.dhumal\workspace\Pentest\node_modules\express\lib\router\index.js:166:38)

你可以帮我解决我犯错误的地方吗?

0 个答案:

没有答案