gpt4 book ai didi

node.js - TypeError : req. flash 不是一个函数 - 尝试移动中间件

转载 作者:太空宇宙 更新时间:2023-11-04 02:08:45 25 4
gpt4 key购买 nike

我正在为学校做一个项目,一直在努力找出原因

TypeError: req.flash is not a function

在我的路由中。

我进行了详尽的研究,发现以下解决方案似乎对其他人有效,但对我无效:

  • 确保为本地策略设置了 passReqToCallback: true 并且“back”的大小写为小写。
  • 我已将 app.use(flash()) 移动到中间件堆栈中的各个位置,并确保它位于我的路由声明之前。

这是我所拥有的。服务器.js

    'use strict';

// Set Up =============================================
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var ejs = require('ejs');
var app = express();

var passport = require('passport');
var flash = require('connect-flash');

const PORT = 8081; //For simplicity, since you need root to make it on port 80
const HOSTNAME = "127.0.0.1";

// Config =============================================

require('./app/auth')(passport); //Configure passport

app.use(morgan('dev')); //Logs to the console
app.use(cookieParser()); //Cookies for Auth
app.use(bodyParser.urlencoded({
extended: true
})); //Get info from html forms
app.use(bodyParser.json());

app.set('view engine', 'html'); //Use the template module to render html
app.engine('html', ejs.renderFile);
app.set('views', __dirname + "/public/views/pages"); //Instruct the engine of the location of the views


app.use(session({
secret: 'hashmeupsomethinggood',
resave: true,
saveUninitialized: true
})); //Set default values
app.use(passport.initialize());
app.use(passport.session()); //Login sessions
app.use(flash()); //For 'Flashing' messages back to client


app.use(express.static(__dirname +'/public')); //Serves static files to client

// Routing =============================================

//Initialize routing with application and configured passport
require('./app/routes.js')(app, passport);

// Run ==================================================

//Run the server
var server = app.listen(PORT, HOSTNAME, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port)
});

routes.js

module.exports = function (app, passport) {

app.get('/', function (req, res) { //Callback for main pages
res.render("index.html");
});

app.get('/movies', function (req, res) { //Callback for movies display
res.render("movies.html");
});

//Handler for User Login
app.post('/userlogin',
passport.authenticate('local-login', {
failureFlash:true
},
function (req, res) {

if (req.user) {
console.log("User " + req.user + " logged in");
res.redirect("index.html"); //redirect but this time will render as logged in
} else {
console.log("Login Attempt");
res.json({flashInfo: req.flash('login')}); //respond with info
}

}
)
);

};

auth.js

var LocalStrategy = require('passport-local').Strategy; //For authenticating email and password
var mysql = require('mysql');
var connection = require('./connection');

//Set up mysql
var sqlCon = mysql.createConnection(connection);

module.exports = function (passport) {

// Session Setup ==============================================================
// Needed for persistent logins

//Serialize user id to identify session
passport.serializeUser(function (user, done) {
console.log("[Auth] Checking Login of " + user.EMAIL);
if (user.ID) //User logging in is a customer OR employee - check both
done(null, user.ID);
else
done(null, user.SSN);
});

//Obtain user object based on session user id
passport.deserializeUser(function (id, done) {

connection.query( //todo: add support for the employee here too
"SELECT * FROM customers WHERE EMAIL = ?",
[id],
function (err, results, field) {
done(err, results[0]);
}
);
});

// Login ==============================================================

passport.use(
'local-login',
new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback : true
},
function (req, email, password, done) {
console.log("[Auth] Checking Login of " + email);
//Query for customer credentials
connection.query("SELECT * FROM customers WHERE EMAIL = ?",
[email],
function (err, results) {
console.log("[Auth] First query");
if (err) {
console.log("[Auth] Error Accessing Database");
return done(err); //Error accessing database
} else {
if (results.length == 0) { //Could possibly be an employee logging in

//Query for employee credentials
connection.query("SELECT * FROM employee WHERE EMAIL = ?",
[email],
function (err, results) {
if (err) {
return done(err); //Query failed
} else {
if (results.length == 0) {//Does it exist in employee either?
console.log("[Auth] Could not find user");
return done(null, false, req.flash("login", "A user by that name does not exist!"));
}
return passwordCheck(results[0]); //Verify password

}

}

)
}
return passwordCheck(results[0]);
}
});

//Determines the validity of a password and returns the corresponding verify callback function
var passwordCheck = function (result) {
console.log("[Auth] Verifying Password of " + email);
if (result.PASSWORD == password)
return done(null, result);
else
return done(null, false, req.flash("login", "Incorrect Password"));

};
}
)
);

// Register ==============================================================

passport.use(
'local-register',
new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback : true
},
function (req, email, password, done) {
//Grab form data
var data = [req.body.fname, req.body.lname, req.body.bday, req.body.gender, email, password] //Form data

//Check that input isnt empty
if (data.includes("")) {
console.log("User %s registed with empty form", email);
return done(null, false, req.flash("register", "Please make sure not to leave anything blank"));
}

//Check that we arent making a duplicate account
connection.query(
"SELECT * FROM customer WHERE EMAIL = ?",
[email],
function (err, results) {
if (err) {
done(err);
}

//Check if the email has been taken
if (results.length > 0) {
done(null, false, req.flash("register", "That email has already been taken"));
} else {

//User for session
var newUser = {
EMAIL: data[4],
PASSWORD: data[5],
FNAME:data[0],
LNAME: data[1],
BDAY: data[2],
SEX: data[3]
};

connection.query(
"INSERT INTO customer(FNAME, LNAME, BDATE, SEX, EMAIL, `PASSWORD`) " +
"VALUES (?, ?, STR_TO_DATE(?, '%m/%d/%y'), ?, ?, ?)",
data,
function (err, results) {
newUser.ID = results.insertId; //Add ID
return done(null, newUser);
}
)

}

})


}
)
);

};

最佳答案

查询时不小心使用了变量connection而不是sqlCon

关于node.js - TypeError : req. flash 不是一个函数 - 尝试移动中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43219504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com