Node.js TypeError:无法读取属性';密码';未定义的

Node.js TypeError:无法读取属性';密码';未定义的,node.js,express,Node.js,Express,我正在学习Node Js和express as ORM,我需要创建用户授权,我已经设法创建了注册后端代码,并通过postman对其进行了测试,它工作得非常完美,挑战来自登录,当我通过postman对其进行测试时,我在我的vscode终端“TypeError:无法读取未定义的属性“password”中发现了此错误我已经试着找出问题所在,但很多解决方案都指出sequelize顺序有问题,即app.use(bodyParser.json());在路线和我的订单正确但仍然有相同的错误之前,应该先到达。请

我正在学习Node Js和express as ORM,我需要创建用户授权,我已经设法创建了注册后端代码,并通过postman对其进行了测试,它工作得非常完美,挑战来自登录,当我通过postman对其进行测试时,我在我的vscode终端“TypeError:无法读取未定义的属性“password”中发现了此错误我已经试着找出问题所在,但很多解决方案都指出sequelize顺序有问题,即app.use(bodyParser.json());在路线和我的订单正确但仍然有相同的错误之前,应该先到达。请问谁能帮我

我的用户(注册和登录代码)

这是邮递员的电脑

这是我的数据库、型号和服务器

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;
分贝

这是用于注册和登录的用户路由

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;

我已经修改了你的代码并对其发表了一些评论。请尝试:

注册路线

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
        });
    });
});

你能试试这个登录路径吗?我用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 });
  }
});

您的注册路径可以重构为async/await,如下所示:

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
    });
  }
});

这意味着您从邮递员发送的请求或您正在使用的任何前端都没有在POST请求in/signup中发送有效负载,您能告诉我您发送的表单数据的有效负载吗?这是说你的身体是未定义的,请检查我上传的图像,我在数据库中注册的用户没有问题,但当我登录时,未定义的错误可能是一个或两个。一个是您的Sequelize没有实际保存密码,另一个是您使用的是
findOne
但使用了数组访问器,或者
req.body.password
只是
未定义的
,我还有一些编辑。您需要
返回User.findOne({…})
才能在下一个承诺中使用结果。您不需要“where”,只需执行
User.findOne({email:req.body.email})
和console.log(User),如果出现错误,则使用Unimizer,它的工作错误已经消失,但当我发送请求登录让我身份验证失败似乎无法比较,任何帮助你有任何新问题的日志吗?尝试记录
req.body.password
user.password
我已尝试调试我的json消息,因此当我发送响应时,我收到的最后一条消息似乎无法比较登录凭据。实际上,我修改了上述代码并添加了一些日志,请您再试一次,看看出现了哪个日志?请检查我上传的屏幕短片,我仍然收到最后一条json消息“Authentication failed Haahahahahahahahah!”评论不用于扩展讨论;这段对话已经结束。
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
        });
    });
});
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
    });
  }
});