InsideDarkWeb.com

Unable to get redis key-value pair using Node.js (ERR_HTTP_HEADERS_SENT)

Trying to fetch key-value pair from my localhost redis client using Node.js.

  1. If I include the res.json() inside the function/for loop, I get HTTP_HEADER error for sending response more than once.

  2. 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)
    });
});

Stack Overflow Asked by nomadev95 on November 18, 2021

1 Answers

One Answer

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

Add your own answers!

Related Questions

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.