gpt4 book ai didi

node.js - 使用 Passport 注册并使用 Sequelize 保存不起作用(意外的 ' ')

转载 作者:行者123 更新时间:2023-12-03 22:39:34 26 4
gpt4 key购买 nike

我的 Node.js 项目的 Passport 和 Sequelize 有一些问题。
事实上,当我想注册时,我正在使用 postman 来调用/users/signup 路线,它告诉我: Unexpected '' 和:

::1 - - [07/Aug/2018:09:20:19 +0000] "POST /users/signup HTTP/1.1" - - "-" "PostmanRuntime/7.2.0"
Executing (default): SELECT "user_id", "username", "name", "firstname", "email", "type", "location", "password", "createdAt", "updatedAt" FROM "users" AS "users" LIMIT 1;

有代码:
/* CREATE an account */
app.post('/users/signup', (req, res) => {

db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] }).then(user => {

if (err) {
return res.send(err);
}
if (user) {
if (user.email == req.body.email) {
return res.send("This email is already taken.")
}
return res.send("This username is already taken.")
}
else {

const data = {
username: req.body.username,
name: req.body.name,
firstname: req.body.firstname,
email: req.body.email,
location: req.body.location,
type: req.body.type,
password: req.body.password
};

db.users.create({
username: data.username,
name: data.name,
firstname: data.firstname,
email: data.email,
location: data.location,
type: data.type,
password: data.password

}).then(newUser => {
res.send("newUser saved to database")
// `req.user` contains the authenticated user.
//TODO : res.redirect('/profile/' + req.body.username);
})
.catch(err => {
console.log(err);
res.status(400).send("unable to save this newUser to database");
})

}

}).catch(err => {
console.log(err);
res.status(400).send("signup failed");
})

})

我的模型(db.users):
const bcrypt = require("bcrypt-nodejs");

module.exports = (sequelize, DataTypes) => {
// TABLE USERS
const Users = sequelize.define('users', {

user_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
firstname: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
type: {
type: DataTypes.STRING,
allowNull: false,
},
location: {
type: DataTypes.STRING
},
password: {
type: DataTypes.STRING,
allowNull: false
}
});

// methods ======================
// generating a hash
Users.generateHash = function (password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};

// checking if password is valid
Users.validPassword = function (password) {
return bcrypt.compareSync(password, this.password);
};

//hashing a password before saving it to the database
Users.beforeCreate('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
})
});

return Users;
};

我的 Passport .js :
// load all the things we need
var LocalStrategy = require('passport-local').Strategy;
var db = require('../db')

// expose this function to our app using module.exports
module.exports = function (passport) {

var User = db.users;
// =========================================================================
// passport session setup ==================================================
// =========================================================================
// required for persistent login sessions
// passport needs ability to serialize and unserialize users out of session

// used to serialize the user for the session
passport.serializeUser(function (user, done) {
done(null, user.id);
});

// used to deserialize the user
passport.deserializeUser(function (id, done) {
User.find({
where: { user_id: user_id }
})
.then(function (user) {
done(err, user);
}).catch(function (err) {
return done(err);
})
});


// =========================================================================
// LOCAL LOGIN =============================================================
// =========================================================================
// we are using named strategies since we have one for login and one for signup
// by default, if there was no name, it would just be called 'local'

passport.use('local-login', new LocalStrategy({
// by default, local strategy uses username and password, we will override with email
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true // allows us to pass back the entire request to the callback
},
function (req, email, password, done) { // callback with email and password from our form

// find a user whose email is the same as the forms email
// we are checking to see if the user trying to login already exists
User.findOne({ email : email }, function (err, user) {
// if there are any errors, return the error before anything else
if (err)
return done(err);

// if no user is found, return the message
if (!user)
return done(null, false, { message: 'User not found.' }); // req.flash is the way to set flashdata using connect-flash
// if the user is found but the password is wrong
if (!user.validPassword(password))
return done(null, false, { message: 'Incorrect password.' }); // create the loginMessage and save it to session as flashdata

// all is well, return successful user
return done(null, user);
});

}));

};

我找不到问题的根源。我是 Node.js 的新手,几个小时后我就被困住了。请问这里有人可以帮助我吗?

最佳答案

经过讨论,我们发现第一个错误来自beforeSave。钩在 User db 模型上,其中使用的散列函数缺少 null参数作为第三个参数,因此 bcrypt 抛出“未通过回调”错误。还有其他一些问题,例如误用 promise 和回调,我建议通过学习 promise ,并仔细检查有关如何使用库的文档和示例,例如 Sequelize 和 bcrypt(如何生成和使用例如盐)。

上一个答案

我认为问题出在你的“本地登录”策略: Passport 使用回调,但 Sequelize 使用 promise ,所以你的 User.findOne回调永远不会被调用。尝试这样的事情:

app.post("/users/signup", (req, res) => {
return db.users
.find({
$or: [
{
email: req.body.email
},
{
username: req.body.username
}
]
})
.then(user => {
if (user) {
if (user.email == req.body.email) {
return res.send("This email is already taken.");
}
return res.send("This username is already taken.");
} else {
return db.users
.create({
username: req.body.username,
name: req.body.name,
firstname: req.body.firstname,
email: req.body.email,
location: req.body.location,
type: req.body.type,
password: req.body.password
})
.then(newUser => {
res.send("newUser saved to database");
});
}
})
.catch(err => {
console.error(err);
res.status(400).send("unable to save this newUser to database");
});
});

路线也一样,反序列化:
app.post('/users/signup', (req, res) => {
db.users.find({ $or: [{ email: req.body.email }, { username: req.body.username }] })
.then(user=>{})
.catch(err=>{})

关于node.js - 使用 Passport 注册并使用 Sequelize 保存不起作用(意外的 ' '),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723360/

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