w.phat
w.phat

Reputation: 3

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client in Express.js

I read json file to query with req.params and I want to return res.json but I get error from express.js

_http_outgoing.js:482
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

in route.js

module.exports = (app) => {
  app.get('/find/:province', province.find);
}

in controller.js

exports.find = function (req, res) {
  fs.readFile('./app/models/province_file.json', function(err, provinces){
    if (err) throw err;
    let obj_provinces = JSON.parse(provinces);
    let province = req.params.province;
    for (var i = 0; i < obj_provinces.features.length; i++) {
      if (obj_provinces.features[i].properties.tb_tn == province) {
        let obj_result = obj_provinces.features[i].properties;
        console.log(obj_result);
        res.json(obj_result);
      }
    }
  });
}

when I run the code I get error

_http_outgoing.js:482
    throw new ERR_HTTP_HEADERS_SENT('set');
    ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:482:11)
    at /Users/workspace/app/controllers/controller.js:87:13
    at FSReqCallback.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:54:3)

Upvotes: 0

Views: 5832

Answers (1)

Amol B Jamkar
Amol B Jamkar

Reputation: 1257

Do not call res.json(obj_result); in for loop, let your loop done the work then call res.json(obj_result);;

Because in if res.json(obj_result) is getting called more than once that's why you are getting this error.

It's best practice to use return when you done the execution, it make sure execution is ended at that point.

return res.json(obj_result);

Upvotes: 3

Related Questions