Изучаю Node js. Вылетает ошибка при логине пользователя

Рейтинг: 0Ответов: 0Опубликовано: 05.02.2023

Всем привет! При логине пользователя вылетает ошибка при попытке сделать запрос через Postman.

Error: data and hash arguments required
at Object.compare (/home/anatoliy/templates/fu`введите сюда код`ll-stack- 
app/node_modules/bcrypt/bcrypt.js:208:17)
at /home/anatoliy/templates/full-stack-app/node_modules/bcrypt/promises.js:29:12
at new Promise (<anonymous>)
at module.exports.promise (/home/anatoliy/templates/full-stack- 
app/node_modules/bcrypt/promises.js:20:12)
at Object.compare (/home/anatoliy/templates/full-stack- 
app/node_modules/bcrypt/bcrypt.js:204:25)
at file:///home/anatoliy/templates/full-stack-app/index.js:32:42
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Вот сам код.

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema(
  {
    fullName: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    passwordHash: { type: String, required: true }, //, sparse: true
    avatarUrl: String,
  },
  { timestamps: true }
);

export default mongoose.model("User", UserSchema);

app.post("/auth/login", async (req, res) => {
  try {
    const user = await UserSchema.findOne({ email: req.body.email });

    if (!user) {
      return res.status(404).json({ message: "Неверный логин или пароль." });
    }

    const isValidPassword = await bcrypt.compare(
      req.body.password,
      user._doc.password
    );

    if (!isValidPassword) {
      return res.status(404).json({ message: "Неверный логин или пароль." });
    }

    const token = jwt.sign(
      {
        _id: user._id,
      },
      "secret12345",
      { expiresIn: "30d" }
    );

    const { password, ...userData } = user._doc;
    console.log("user._doc", user._doc);

    res.json({ ...userData, token });
  } catch (error) {
    console.log(error);
    res.status(500).json({ message: "Не удалось авторизоваться." });
  }
});

Очень много времени потерял на усранение ошибки. Заранее благодарю!

Ответы

Ответов пока нет.