繁体   English   中英

从 controller 方法响应没有明确响应

[英]Respond from controller method without express response

我正在尝试响应,以防一个项目的获取没有从另一个没有快速响应的方法返回一些东西。 我从另一个调用这个方法,如果它有明确的响应:

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    await itemExists( id, idItem);

...

在 itemExists() function 中,我在 mongo 中搜索该项目,如果它不存在,我想将其作为响应发送,但如果不使用 Express 响应,我不知道该怎么做:

const itemExists = async ( id, idItem ) => {

    const item = await PettyCashItems.findOne({ _id: id, "items._id": idItem });

    if (!item) {
        return ......
    }
}

谢谢。

正如其中一条评论已经提到的那样,如果没有访问权限,就无法使用响应 object。

但是,您想要的可以通过两种方式实现:

1- 简单的方法 - 从 itemExists function 返回一个值,并根据 itemExists 的返回值发送响应

const updateItem = async (req, res = response ) => {

    const id = req.params.id;
    const idItem = req.params.idItem; 

    const exists = await itemExists( id, idItem);

    if (exists) {
      res.send('YES')
      return;
    }

    res.send('NO');
}

2-更好的方法-为您的快速应用程序设置错误处理,以便捕获所有抛出的错误并根据抛出的错误发送响应,然后您可以简单地

class BaseHTTPException extends Error {
  constructor(statusCode) {
    super();
    this.statusCode = statusCode;
  }

}


class ItemDoesNotExistException extends BaseHTTPException {
  constructor() {
    super(400)
  }
}

throw new ItemDoesNotExistException()

在您的项目中存在 function。

进一步阅读: https://expressjs.com/en/guide/error-handling.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM