【问题标题】:return response in a function in express app在快速应用程序的函数中返回响应
【发布时间】:2019-02-25 08:06:32
【问题描述】:

如我们所知,我们必须在 express 应用中返回响应以避免 “无法在将标头发送到客户端后设置标头” 错误。 但是,在下面的代码中,我试图返回响应,但它正在返回到我们的路由器并导致提到的错误。如何在函数中直接返回响应?

router.post("/admins", async function (req, res) {

    var newAdminObj = await newAdminObjectDecorator(req.body, res);

    var newAdmin = new Admins(newAdminObj)

    newAdmin.save(function (err, saveresult) {
        if (err) {
            return res.status(500).send();
        }
        else {
            return res.status(200).send();
        }
    });
});



// the function
var newAdminObjectDecorator = async function (entery, res) {

    // doing some kinds of stuff in here

    // if has errors return response with error code
    if (err) {
        // app continues after returning the error header response
        return res.status(500).send();
    }
    else {
        return result;
    }
}

【问题讨论】:

  • 直接抛出错误而不是 res.status(500).send
  • 谢谢,但这是最佳做法吗?您能否解释更多(作为答案)关于 throw 和解决此问题的其他方法(如果存在)?

标签: javascript node.js express


【解决方案1】:

切勿运行控制器功能以外的响应操作。让其他函数返回答案,根据答案决定。

router.post("/admins", async function (req, res) {

    var newAdminObj = await newAdminObjectDecorator(req.body);

    if (newAdminObj instanceof Error) {
        return res.status(500).send()
    }

    var newAdmin = new Admins(newAdminObj)

    newAdmin.save(function (err, saveresult) {
        if (err) {
            return res.status(500).send();
        }
        else {
            return res.status(200).send();
        }
    });
});



// the function
var newAdminObjectDecorator = async function (entery) {

    // doing some kinds of stuff in here

    // if has errors return response with error code
    if (err) {
        // app continues after returning the error header response
        return err;
    }
    else {
        return result;
    }
}

【讨论】:

  • Teşekkür ederim.
猜你喜欢
  • 2018-10-22
  • 2011-03-12
  • 2019-04-27
  • 2016-02-25
  • 2018-08-14
  • 2022-11-19
  • 2016-06-21
  • 2018-12-25
  • 1970-01-01
相关资源
最近更新 更多