我是nodejs(v4.5)&的新手。表达(v4),我正在尝试使用护照js(本地)创建登录。我尝试了很多,但我总是得到401错误。我也检查了论坛但找不到解决方案。 Express-session是v1.5。
这是我的代码: 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 session = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var base = require('./base');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
require('./config/passport')(passport);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'vidyapathaisalwaysrunning',
resave: false,
saveUninitialized: true
} ));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
app.use(function (req, res, next) {
req.rooturl = req.protocol + '://' + req.get('host') + '/';
next();
});
require('./routes/admin')(app, passport);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
db.js
var mysql = require('mysql');
var sqlConnection = function sqlConnection(sql, values, next) {
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
port: 3306,
database : 'test'
});
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
}
});
connection.query(sql, values, function(err) {
connection.end();
if (err) {
throw err;
}
// Execute the callback
next.apply(this, arguments);
});
}
module.exports = sqlConnection;
admin.js
var db = require('../config/db');
module.exports = function(app, passport){
app.get('/admin', function(req, res) {
res.render('login/admin', {
rooturl: req.rooturl,
title: 'Crud'
});
});
app.post('/admin', passport.authenticate('local-login'), function(req, res) {
res.json('5');
});
};
admin.ejs
$('#login').validate({
submitHandler: function(form){
var data = $(form).serialize();
$.ajax({
type:'post',
url: document.url,
//data: new FormData(form),
data: data,
processData: false,
cache: false,
success: function(d){
alert(JSON.stringify(d));
}
});
return false;
}
});
passport.js
var LocalStrategy = require('passport-localapikey').Strategy;
var db = require('./db');
module.exports = function(passport) {
// console.log('5');
passport.serializeUser(function(user, done) {
console.log('4');
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db("SELECT * FROM user WHERE id = ? ",[id], function(err, rows){
console.log('6');
done(err, rows[0]);
});
});
passport.use('local-login',
new LocalStrategy({
usernameField : 'email',
passwordField : 'password',
passReqToCallback : true
},
function(req, username, password, done) {
console.log(username);
db("SELECT * FROM user WHERE email = ? and password = ?",[username, password], function(err, rows){
console.log('2');
if (err)
return done(err);
if (!rows.length) {
return done(null, false, req.flash('loginMessage', 'No user found.'));
}
if(password != rows[0].password){
return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.'));
}
return done(null, rows[0]);
});
})
);
}