我正在尝试使用passport.js实现Express注册,当我提交表单时,在服务器控制台上我得到:
POST /user/register 500 62.273 ms - 2008
TypeError: User is not a constructor
at /mean-auth/server/routes/api.js:8:17
下面是错误的api.js文件:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var User = require('../models/user.js');
router.post('/register', function(req, res) {
User.register(new User({ username: req.body.username }),
req.body.password, function(err, account) {
if (err) {
return res.status(500).json({
err: err
});
}
passport.authenticate('local')(req, res, function () {
return res.status(200).json({
status: 'Registration successful!'
});
});
});
});
module.exports = router;
用户模型(user.js
)如下图:
// user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var bcrypt = require('bcrypt');
var userSchema = mongoose.Schema({
username: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
var User = mongoose.model('User', userSchema);
module.exports = {
User: User
};
module.exports.createUser = function(newUser, callback){
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
});
});
}
module.exports.getUserByUsername = function(username, callback){
var query = {username: username};
User.findOne(query, callback);
}
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err) throw err;
callback(null, isMatch);
});
}
和我也尝试了createUser
方法和newUser
对象:
var User = require('../models/user.js');
router.post('/register', function(req, res) {
var username = req.body.username;
var password = req.body.password;
var newUser = new User({
username: username,
password: password
});
User.createUser(newUser, function(err, user){
if(err) throw err;
console.log(user);
});
passport.authenticate('local')(req, res, function () {
return res.status(200).json({
status: 'Registration successful!'
});
});
});
,但出现相同的错误。用户的定义有什么问题吗?
似乎您正在导出一个对象,其中包含User。
module.exports = {
User: User
};
当导入该文件时,尝试这样做:
var User = require('../models/user.js').User;
在require语句中不需要.js
扩展。
var User = require('../models/user');