Pouya Jabbarisani
Pouya Jabbarisani

Reputation: 1121

return response in a function in express app

As we know, we must return the response in the express app to avoid "Cannot set headers after they are sent to the client" error. However, In below code, I'm trying to return the response but It's returning to our router and causes mentioned error. how I can directly return the response in function?

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

Upvotes: 5

Views: 3315

Answers (1)

Halil SAFAK
Halil SAFAK

Reputation: 377

Never run a response operation other than the controller's functions. Let the other function return the answer and decide according to the answer.

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

Upvotes: 5

Related Questions