在使用服务器进行身份验证时,服务器不响应POST请求。服务器接收请求并正确解析JSON,但它从不发送响应。我已经按照许多指南和更新的节点无济于事。
代码相当简单,相关部分是:
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 bodyParser = require('body-parser');
var session = require('express-session');
var mongoose = require('mongoose');
var connectMongo = require('connect-mongo');
var debug = require('debug')('sess:app');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var index = require('./routes/index');
var home = require('./routes/home');
var about = require('./routes/about');
var catalog = require('./routes/catalog');
var branches = require('./routes/branches');
var users = require('./routes/users');
var dbconnect = require('./dbconnect');
var app = express();
var MongoStore = connectMongo(session);
var sessionConnect = dbconnect.Session;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(cookieParser());
app.use(session({
name: '...',
secret: '...',
resave: false,
saveUninitialized: false,
rolling: true,
store: new MongoStore({ mongooseConnection: sessionConnect }),
cookie: { maxAge: 900000, httpOnly: true, sameSite: true }
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
// passport setup
var User = require('./models/user')(dbconnect.Models);
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// Create user for testing
User.create({username:'admin',password:'12345',deleted:false,kind:'manager'});
// login
// This was attempted with additional redirection options as well
app.post('/login', passport.authenticate('local'), function(req, res) {
// This message never appears in the log
console.log('auth');
res.status(200).end();
});
// logout
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
// 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 handler
app.use(function(err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
dbconnect.js:
var mongo = require("mongoose");
mongo.Promise = global.Promise;
var debug = require('debug')('sess:app');
function dbconnect(path){
var userConnStr = 'mongodb://localhost:27017/ise_' + path + '_v6';
var db = mongo.createConnection()
db.on('connecting', function() { debug('Connecting to MongoDB: '); });
db.on('connected', function() { debug('Connected to MongoDB: '); });
db.on('disconnecting', function() { debug('Disconnecting to MongoDB: '); });
db.on('disconnected', function() { debug('Disconnected to MongoDB: '); });
db.on('reconnected', function() { debug('Reconnected to MongoDB: '); });
db.on('error', function(err) { debug('Error to MongoDB: ' + err); });
db.on('open', function() { debug('MongoDB open : '); });
db.on('close', function() { debug('MongoDB close: '); });
process.on('SIGINT', function() { db.close(function () { process.exit(0); });});
db.openUri(userConnStr);
console.log('Pending DB connection');
return db;
};
module.exports = {Session: dbconnect('session'), Models: dbconnect('models'), Custom: dbconnect};
模型/ user.js的:
var mongo = require("mongoose");
var Schema = mongo.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var userSchema = new Schema({ // create a schema
name: { first: String, last: String }, // field-object (with sub-fields)
kind: { type: String, required: true, enum: ["manager", "employee", "customer", "supplier"] },
email: String,
branch: Number,
created_at: Date,
updated_at: Date,
deleted: { type: Boolean, required: true }
});
userSchema.plugin(passportLocalMongoose);
userSchema.methods.remove = function() {
deleted = true;
save();
};
// on every save, add the date
userSchema.pre('save', function(next) { //callback
// get the current date
var currentDate = new Date();
// change the updated_at field to current date
this.updated_at = currentDate;
// if created_at doesn't exist, add to that field
if (!this.created_at)
this.created_at = currentDate;
next();
});
module.exports = function(db){
return db.model('User', userSchema);
};
客户端代码使用AngularJS v1:
控制器功能:
$scope.signin = function(){
$http.post("login", {'username': $scope.username, 'password': $scope.password}).then(function(data){
// ......
}, function(data){
alert("Wrong username or password");
});
};
HTML Bootstrap模式:
<div id="signInModal" class="modal fade" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Sign in</h4>
</div>
<form>
<div class="modal-body">
<div class="form-group">
<input ng-model="username" type="text" placeholder="Username" class="form-control">
</div>
<div class="form-group">
<input ng-model="password" type="password" placeholder="Password" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" ng-click="signin()">Sign in</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>