Node noob并且第一次在这里问一个问题,所以我希望我能做到这一点..
我使用https://github.com/jkvoorhis/userAuth作为格式化代码的基础,用Mongoose方法替换Orchestra。
每当我向/ register发送POST请求时,我在节点窗口中的响应都是:
null
username already exists
COULD NOT REGISTER
POST /register 302
GET /failed 304
当MongoDB中的文档存在时,为什么它会一直返回null? User.findOneQ({"username": username})
有什么问题吗?我弄乱了mongoose = require('mongoose-q')()
吗?非常感谢你。
App.js:
var express = require('express'),
http = require('http'),
path = require('path'),
mongoose = require('mongoose'),
passport = require('passport'),
LocalStrategy = require('passport-local'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session'),
session = require('express-session'),
redis = require('redis'),
RedisStore = require('connect-redis')(session);
var Config = require('./config/config.js');
var app = module.exports = express();
var auth = require('./server/controllers/auth');
//mongo
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL || Config.mongo.address
mongoose.connect(mongoUri);
app.set('views', __dirname + '/client/views');
app.set('view engine', 'jade');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(express.static(path.join(__dirname, 'client')));
//redis session cookie
app.use(cookieParser());
app.use(session({
store: new RedisStore({
host: Config.redis.host,
port: Config.redis.port,
pass: Config.redis.pass
}),
secret: '1234567890QWERTY'
}));
// Passport session setup.
passport.serializeUser(function(user, done) {
console.log("serializing " + user.username);
done(null, user);
});
passport.deserializeUser(function(obj, done) {
console.log("deserializing " + obj);
done(null, obj);
});
// Use the LocalStrategy within Passport to Register/"signup" users.
passport.use('local-register', new LocalStrategy(
{passReqToCallback : true}, //allows us to pass back the request to the callback
function(req, username, password, done) {
auth.register(username, password)
.then(function (user) {
if (user) {
console.log("REGISTERED: " + user.username);
req.session.success = 'You are successfully registered and logged in ' + user.username + '!';
done(null, user);
}
if (!user) {
console.log("COULD NOT REGISTER");
req.session.error = 'That username is already in use, please try a different one.'; //inform user could not log them in
done(null, user);
}
})
.fail(function (err){
console.log(err.body);
});
}
));
// Simple route middleware to ensure user is authenticated.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.session.error = 'Please sign in!';
res.redirect('/signin');
}
app.post('/register', passport.authenticate('local-register', {
successRedirect: '/success',
failureRedirect: '/failed'
})
);
app.post('/login', function(req,res){
var data = req.body;
console.log(data.username + ' ' + data.password);
res.send(data.username + ' ' + data.password);
});
app.post('/logout', function(req,res){
res.send('logout page');
});
app.get('/users', function(req, res){
res.send('hello world');
});
app.get('/success', function(req,res){
res.send('it was a success!');
})
app.get('/failed', function(req,res){
res.send('it faaailed!');
});
var port = Number(process.env.PORT || 8000);
app.listen(port, function() {
console.log("Listening on " + port);
});
Auth.js:
var bcrypt = require('bcrypt-nodejs'),
mongoose = require('mongoose-q')(),
User = require('../models/UserSchema'),
Q = require('q');
exports.register = function (username, password) {
var deferred = Q.defer();
var hash = bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
var user = {
"username": username,
"password": hash
};
//check if username is already assigned in our database
User.findOneQ({"username": username})
.then(function (result){ //case in which user already exists in db
// console.log('result' + result.body);
console.log(result);
console.log('username already exists');
deferred.resolve(false); //username already exists
})
.fail(function (result) {//case in which user does not already exist in db
console.log(result.body);
if (result.body.message == 'The requested items could not be found.'){
console.log('Username is free for use');
user.saveQ()
.then(function(){
console.log('user saved!');
deferred.resolve(user);
})
.fail(function (err) {
console.log("PUT FAIL:" + err.body);
deferred.reject(new Error(err.body));
});
} else {
deferred.reject(new Error(result.body));
}
});
return deferred.promise;
};
user.js的:
var mongoose = require('mongoose');
//user
var UserSchema = new mongoose.Schema({
username: { type: String },
password: { type: String }
}, {collection: 'User'});
module.exports = mongoose.model('User', UserSchema);