当前位置: 代码迷 >> JavaScript >> 在快递应用程序中的函数中返回响应
  详细解决方案

在快递应用程序中的函数中返回响应

热度:82   发布时间:2023-06-05 14:07:50.0

我们知道,我们必须在快速应用程序中返回响应,以避免“在发送到客户端后无法设置标头”错误。 但是,在下面的代码中,我试图返回响应但它返回到我们的路由器并导致提到的错误。 我怎样才能直接返回函数中的响应?

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;
    }
}

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

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;
    }
}
  相关解决方案