0

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)
w.phat
  • 3
  • 1
  • 3

1 Answers1

3

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);
Amol B Jamkar
  • 1,227
  • 10
  • 19
  • oh, thank you I try return res.json(obj_result); but I get 1 object from 15 object. I wrong? – w.phat May 16 '19 at 07:36
  • Please refer back to this comment, [link](https://stackoverflow.com/a/7086621/6076712) and yes you are trying to override response in a for loop – M.Elfeky May 16 '19 at 08:04