Axios.delete не работает так, как я этого хочу - PullRequest
0 голосов
/ 08 ноября 2018

Это приложение для тренажерного зала, которое, когда пользователь записывает себя в класс, класс сохраняет userId как пользователя, который будет посещать, тогда также в модели пользователя вы также получаете классы, в которых учится пользователь.

В настоящее время ударяет 500 (Internal Server Error).

Это axios звонки:

deleteClassHandler = () => {
    this.deleteUserClassHandler();
    const data = {
      userId: this.props.userId,
      classId: this.props.id
    }
    axios.delete('/api/classes/remove', data)
      .then(response => {
          console.log(response);
      })
      .catch(error => {
          console.log(error);
      });
}

deleteUserClassHandler = () => {
    const data = {
      userId: this.props.userId,
      classId: this.props.id
    }
    axios.delete('/api/auth/remove', data)
      .then(response => {
        console.log(response);
      })
      .catch(error => {
        console.log(error);
      });
}

this.props.userID и this.props.id заполняются нормально правильными значениями.

Это маршруты -

Классы маршрутов: router.delete('/remove', ClassesController.deleteUser);

Маршруты аутентификации: router.delete('/remove', UserController.deleteClass);

Это контроллеры:

Контроллер классов -

exports.deleteUser = (req, res) => {
  console.log('cl userid ', req.body.userId);
  console.log('cl classid ', req.body.classId);
  GymClass.findById({
    _id: req.body.classId
  }, 'classMembers', (err) => {
    if (err) {
      console.log('class up here');
      res.status(401).json({
        message: "Error Occured!"
      })
    } else {
      GymClass.findByIdAndDelete({
        "classMembers.userId" : mongoose.Types.ObjectId(req.body.userId)
      }, (err) => {
        if(err) {
          console.log('class down');
            res.status(401).json({
              message: "Error Occured!"
            })
        } else {
          res.status(200).json({
            message: "Success!"
          })
        }
      });
    }
  })
}

Контроллер аутентификации -

exports.deleteClass = (req, res) => {
  console.log('auth userid', req.body.userId);
  console.log('auth classid', req.body.classId);
  User.findById({
    _id: req.body.userId
  }, 'bookedClasses', (err) => {
    if (err) {
      console.log('auth up here');
      res.status(401).json({
        message: "Error Occured!"
      })
    } else {
      GymClass.findByIdAndDelete({
        "bookedClasses.classId" : mongoose.Types.ObjectId(req.body.classId)
      }, (err) => {
        if(err) {
          console.log('auth down here');
            res.status(401).json({
              message: "Error Occured!"
            })
        } else {
          res.status(200).json({
            message: "Success!"
          })
        }
      });
    }
  })
}

Я ни в коем случае не суперзвезда бэкэнда, и я ударил кирпичную стену этим, кто-нибудь здесь знает, как я мог возможно изменить код и способ, которым я занимаюсь этим? Любые проблемы обнаружены? У меня ошибка 500 на сервере , и я не уверен, что делать. Я всегда могу опубликовать две модели для пользователя и классов, если это необходимо.

Я тоже пытался, но это не помогло -

axios.delete('/api/classes/remove', {
        data: {
          userId: this.props.userId,
          classId: this.props.id
        }
      })
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.log(error);
        });
}
...