Search code examples
node.jsangularget

Cannot set headers after they are sent to the client in node js


I am getting this error only when I call get method (Not every time).

Here is my node function which returns me a response.

exports.GetDepartmentList = function (req, res) {
    fs.readFile('./api/tempFiles/department.json', 'utf8', function (err,response) {
        res.status(200).send({
            success: true,
            data: JSON.parse(response)
        });
        return res.json();
        dbConn.close();
    }).catch(function (err) {
        res.status(500).send({
            success: false,
            message: err.message
        });
        return res.json();
        dbConn.close();
    });
};

I already checked all the StackOverflow's questions but none of them are helpful for solving my problem.


Solution

  • This error occured when you send multiple responses to your client side.

    I think you should try with something like this (without catch)

    exports.GetDepartmentList = function (req, res) {
        fs.readFile('./api/tempFiles/department.json', 'utf8', function (err, response) {
            if (err) {
                res.status(500).json({
                    success: false,
                    message: err.message
                });
            }
            else {
                res.status(200).json({
                    success: true,
                    data: JSON.parse(response)
                });
            }
            dbConn.close(); // Really usefull ?
        });
    };
    

    Hope it helps.