我正在学习Node Js,并表示为ORM,我需要创建用户授权,并且已经设法创建了注册后端代码并通过邮递员对其进行了测试,并且它工作得很好,当我通过邮递员对其进行测试时,登录带来了挑战我的vscode终端出现此错误“ TypeError:无法读取未定义的属性'password'”,我试图找出但许多解决方案状态存在续集顺序问题,即app.use(bodyParser.json());应该在路线和我的订单正确之前先到,但仍然得到相同的错误。请谁能帮助我
我的用户(注册和登录代码)
const express = require('express');
const bcrypt = require('bcrypt');
const User = require('../models/users');
const router = express.Router();
router.post('/signup',(req, res, next)=>{
User.findOne({
where:{
email:req.body.email
}
}).then(user=>{
if(user){
res.status(409).json({
message:'Email alreadly exist!'
})
}else{
bcrypt.hash(req.body.password, 10, (err, hash)=>{
if(err){
return res.status(500).json({
error:err
});
}else{
const user =new User({
email:req.body.email,
password: hash
});
user.save()
.then(result=>{
// console.log(result)
res.status(201).json({
message:'User created successfully'
});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
}
})
}
})
});
router.post('/login',(req, res, next)=>{
User.findOne({
where:{
email:req.body.email
}
})
.then(user =>{
if(user.length<1){
return res.status(401).json({
message:'Authentication failed'
});
}
bcrypt.compare(req.body.password, user[0].password, (err, result)=>{
if(err){
return res.status(401).json({
message:'Authentication failed'
});
}
if(result){
return res.status(200).json({
message:'Authorization granted!'
});
}
return res.status(401).json({
message:'Authentication failed'
});
});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
});
module.exports=router;
我的app.js代码
const express = require('express');
const app= express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/orders');
const userRoutes =require('./api/routes/users');
const sequelize =require('./api/config/database');
app.use((req, res, next)=>{
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Headers','Origin, X-Requested, Content-Type, Accept, Authorization');
if(req.method === 'OPTIONS'){
res.header('Access-Control-Allow-Methods','PUT, POST, GET, DELETE');
return res.status(200).json({
});
}
next();//this allow our request to procede
});
app.use('/products',productRoutes);
app.use('/orders',orderRoutes);
app.use('/users',userRoutes);
app.use((req, res, next)=>{
const error =new Error('Page Not Found');
error.status=404;
next(error);
});
app.use((error, req, res, next)=>{
res.status(error.status||500);
res.json({
error:{
message:error.message
}
});
});
sequelize.sync().then(result=>{
// console.log(result);
})
.catch(err=>{
console.log(err);
});
module.exports=app;
Register and login routes
const express = require('express');
const bcrypt = require('bcrypt');
const User = require('../models/users');
const router = express.Router();
router.post('/signup',(req, res, next)=>{
User.findOne({
where:{
email:req.body.email
}
}).then(user=>{
if(user){
res.status(409).json({
message:'Email alreadly exist!'
})
}else{
bcrypt.hash(req.body.password, 10, (err, hash)=>{
if(err){
return res.status(500).json({
error:err
});
}else{
const user =new User({
email:req.body.email,
password: hash
});
user.save()
.then(result=>{
// console.log(result)
res.status(201).json({
message:'User created successfully'
});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
}
})
}
})
});
router.post('/login', async (req, res, next) => {
console.log("req.body: ", req.body);
try {
if (!req.body.email || !req.body.password) {
console.log("Email and password not given");
return res.status(400).send("Email and password is required");
}
const { email, password } = req.body;
let user = await User.findOne({ email });
if (!user) {
console.log("user not found");
return res.status(401).json({ message: 'Authentication failed' });
}
const validPassword = await bcrypt.compare(password, user.password);
if (!validPassword) {
console.log("Password is not valid");
return res.status(401).json({ message: 'Authentication failed' });
}
return res.status(200).json({ message: 'Authorization granted!' });
}
catch (err) {
console.log("Err: ", err);
res.status(500).json({ error: err });
}
});
module.exports=router;
这是我的数据库,模型和服务器
const http = require('http');
const app = require('./app');
const PORT = process.env.PORT||4000;
const server =http.createServer(app);
server.listen(PORT);
用户模型
const Sequelize = require('sequelize');
const sequelize = require('../config/database');
const User = sequelize.define('users',{
id:{
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey:true
},
email:{
type: Sequelize.STRING(50),
required: true,
notEmpty:true,
validate:{
isEmail:true,
},
unique:'email'
},
password:{
type: Sequelize.STRING(30),
required: true
}
});
module.exports=User;
db
const Sequelize = require('sequelize');
const sequelize =new Sequelize('projectone','root','',{
dialect: 'mysql',
host: 'localhost'
});
module.exports=sequelize;
这是用于注册和登录的用户路线
const express = require('express');
const bcrypt = require('bcrypt');
const User = require('../models/users');
const router = express.Router();
router.post('/signup', async (req, res, next) => {
try {
const { email, password } = req.body;
let user = await User.findOne({where:{email}});
if (user) return res.status(409).json({ message: 'Email already exist!' });
user = new User({ email, password });
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
res.status(201).json({ message: 'User created successfully' });
}
catch (err) {
console.log(err);
res.status(500).json({
error: err
});
}
});
router.post("/login", async (req, res, next) => {
try {
if (!req.body.email || !req.body.password) {
return res.status(400).send("Email and password is required");
}
const { email, password } = req.body;
let user = await User.findOne({ where: { email } });
if (!user) {
console.log("user not found");
return res.status(401).json({ message: "Authentication failed" });
}
const validPassword = await bcrypt.compare(password, user.get("password"));
if (!validPassword) {
console.log("Password is not valid");
return res.status(401).json({ message: "Authentication failed" });
}
return res.status(200).json({ message: "Authorization granted!" });
} catch (err) {
console.log("Err: ", err);
res.status(500).json({ error: err });
}
});
module.exports=router;
答案 0 :(得分:0)
我已经修改了您的代码并在其上添加了一些注释。请尝试:
注册路线
router.post('/signup',(req, res, next)=>{
return User.findOne({
where:{
email:req.body.email
}
}).then(user=>{
if(user){
res.status(409).json({
message:'Email alreadly exist!'
})
}else{
bcrypt.hash(req.body.password, 10, (err, hash)=>{
if(err){
return res.status(500).json({
error:err
});
}else{
return User.create({
email: req.body.email,
password: hash
})
.then(result=>{
// console.log(result)
res.status(201).json({
message:'User created successfully'
});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
}
})
}
})
});
登录路线
router.post('/login',(req, res, next)=>{
// .findOne does not return an array and you need to return this Promise to be chainable
return User.findOne({
where:{
email: req.body.email
}
})
.then(user =>{
if(!user) { // User not found!
console.log(`User with ${req.body.email} not found!`);
return res.status(401).json({
message:'Authentication failed'
});
}
const u = user.toJSON();
console.log('User data from DB:', u);
// Changed `user[0].password` to `u.password`
bcrypt.compare(req.body.password, u.password, (err, result)=> {
if(err){
console.error('Error during comparison!', err);
return res.status(401).json({
message:'Authentication error'
});
}
if(result){
console.log('Authentication success!');
return res.status(200).json({
message:'Authorization granted!'
});
}
return res.status(401).json({
message:'Authentication failed'
});
});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
});
答案 1 :(得分:0)
您可以尝试使用此登录路径吗,我使用async / await转换了代码并处理了所有可能性,即使问题仍然存在,它也会为您提供所有信息,这是错误的。
请注意,找到用户后,可以像这样从 user.get(“ password”)检索密码:
router.post("/login", async (req, res, next) => {
try {
if (!req.body.email || !req.body.password) {
return res.status(400).send("Email and password is required");
}
const { email, password } = req.body;
let user = await User.findOne({ where: { email } });
if (!user) {
console.log("user not found");
return res.status(401).json({ message: "Authentication failed" });
}
const validPassword = await bcrypt.compare(password, user.get("password"));
if (!validPassword) {
console.log("Password is not valid");
return res.status(401).json({ message: "Authentication failed" });
}
return res.status(200).json({ message: "Authorization granted!" });
} catch (err) {
console.log("Err: ", err);
res.status(500).json({ error: err });
}
});
您的注册路由可以重构为异步/等待,如下所示:
router.post('/signup', async (req, res, next) => {
try {
const { email, password } = req.body;
let user = await User.findOne({where:{email}});
if (user) return res.status(409).json({ message: 'Email already exist!' });
user = new User({ email, password });
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
await user.save();
res.status(201).json({ message: 'User created successfully' });
}
catch (err) {
console.log(err);
res.status(500).json({
error: err
});
}
});