NodeJS 未处理的承诺拒绝警告:验证错误:

ymdaylpp  于 2022-11-04  发布在  Node.js
关注(0)|答案(1)|浏览(147)

我是一名学生,我试图创建一个预订API,我需要验证登录的用户是否是允许添加课程的管理员,如果不是管理员,将返回访问被拒绝。

module.exports.addCourse = (reqBody) => {
    let newCourse = new Course({
        name : reqBody.name,
        description : reqBody.description,
        price : reqBody.price
    });

    return newCourse.save().then((course,error) => {

        if (!req.user.isAdmin) {

            return res.status(401).send({ message: "Access denied" });;

        } else if (reqBody.isAdmin = true){

            return true;

        };

    });

};

router.post("/",auth.verify,(req,res)=>{

    const data ={
        course: req.body,
        isAdmin: auth.decode(req.headers.authorization).isAdmin
    }
    courseController.addCourse(data).then(resultFromController=>res.send(resultFromController));
});

module.exports = router;

如果用户是管理员,我想在我的数据库中添加该课程,如果不是管理员,则不允许,我总是得到错误:
(node:17308)未处理的承诺拒绝警告:验证错误:课程验证失败:name:课程为必填项,说明:描述为必填项,价格:价格为必填项
即使我已经给出了名称描述和价格,也在 Postman 中添加了令牌。

3vpjnl9f

3vpjnl9f1#

你为什么要使用回调和承诺?你的语法不对...
//修改1

module.exports.addCourse = (reqBody) => {
  const newCourse = new Course({
    name : reqBody.name,
    description : reqBody.description,
    price : reqBody.price
  });

  return newCourse.save()
    .then((course) => {
     // ...code
    }).catch((err) => {
      // code error
    })
}

router.post("/",auth.verify,(req,res)=>{

  const data ={
      course: req.body,
      isAdmin: auth.decode(req.headers.authorization).isAdmin
  }
  courseController.addCourse(data).then(resultFromController=>res.send(resultFromController));
});

module.exports = router;

//修改2

module.exports.addCourse = async (reqBody) => {
  const newCourse = new Course({
    name : reqBody.name,
    description : reqBody.description,
    price : reqBody.price
  });

  return await newCourse.save()
}

router.post("/",auth.verify, async (req,res)=>{

  const data ={
      course: req.body,
      isAdmin: auth.decode(req.headers.authorization).isAdmin
  }

  try {
    const response = await courseController.addCourse(data)
    // response
  } catch (err) {
    // error response
  }
});

module.exports = router;

//修改3

module.exports.addCourse = (reqBody) => {
  const newCourse = new Course({
    name : reqBody.name,
    description : reqBody.description,
    price : reqBody.price
  });

  return new Promise((resolve, reject) => {
    newCourse.save()
      .then((course) => {
        resolve(course)
      }).catch((err) => {
        reject(err)
      })
  })
}

router.post("/",auth.verify,(req,res)=>{

  const data ={
      course: req.body,
      isAdmin: auth.decode(req.headers.authorization).isAdmin
  }

  return new Promise((resolve, reject) => {
    courseController.addCourse(data)
      .then((resultFromController) => {
        resolve(res.send(resultFromController))
      }).catch((error) => { 
        reject(res.send('error'))
      })

  })
});

相关问题