Stack Overflow Asked by nomadev95 on November 18, 2021
Trying to fetch key-value pair from my localhost redis client using Node.js.
If I include the res.json()
inside the function/for loop, I get HTTP_HEADER error for sending response more than once.
If I define it outside the function/loop, I get an empty array.
Error:
_http_outgoing.js:485
throw new ERR_HTTP_HEADERS_SENT('set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Below is the code for app.js
router.get('/route1', function(req, res)
{
var valarr=[];
client.keys('*', function(err, keys) {
console.log(keys);
for(var i=0;i<keys.length;i++){
client.get(keys[i], function (error, value) {
if (err) return console.log(err);
console.log(value);
valarr.push(value);
// res.json({result1:keys, result2:valarr});
//I get ERR_HTTP_HEADERS_SENT if res.json() is defined here
});
}
console.log(valarr); //Empty
res.json({result1:keys, result2:valarr});
//Returns an empty array (valarr)
});
});
You getting (ERR_HTTP_HEADERS_SENT), because you are not checking if value variable have value or not. Just add condition using IF to check value variable. If value will have value then only it will be added in valarr array and will send updated valarr array as response.
SOLUTION :
router.get('/route1', function(req, res)
{
var valarr=[];
client.keys('*', function(err, keys) {
console.log(keys);
for(var i=0;i<keys.length;i++){
client.get(keys[i], function (error, value) {
if (err) return console.log(err);
if(value){
console.log(value);
valarr.push(value);
res.json({result1:keys, result2:valarr});
}
});
}
console.log(valarr); //Empty
res.json({result1:keys, result2:valarr});
//Returns an empty array (valarr)
});
});
Answered by s4suryapal on November 18, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP