node.jsexpressldapjs

getting Error as 'Error: Can't set headers after they are sent' in my node.js service


Below is my code,

app.get("/getList", function (req, resp) {
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var client = ldap.createClient({
        url: 'ldap://my_ip:389'
    });

    client.bind('cn=pratik', 'pratik', function (err) {
        return resp.send(err);
    });

    var opts = {
        filter: '(objectclass=classToSearch)',
        scope: 'sub',
        attributes: ['ipaddress']
      };
      var entries= {};
      var i=0;
      client.search('o=a', opts, function(err, res) {


        res.on('searchEntry', function(entry) {
          console.log('entry: ' + JSON.stringify(entry.object));
            oxe[i] = entry.object;
            i++;
        });
        res.on('end', function(result) {
            console.log("pratik");
            console.log(entries);
            return resp.send(entries);
          });
});

Here when I print the entries, it shows correct result but it doesn't send the response. I can see error as 'Error: Can't set headers after they are sent'. below is the complete Error:

_http_outgoing.js:357
throw new Error('Can\'t set headers after they are sent.');
^

Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:357:11)

How can I resolve this error?


Solution

  • It's because you call resp.send twice: in the client.bind callback and in the res.on("end") callback.

    I'd suggest putting the second job inside of the bind callback, so that you can check the error, and if there is one, you stop there.

    If that succeeds, then I will send the entries.

    app.get("/getList", function(req, resp) {
      process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
      var client = ldap.createClient({
        url: 'ldap://my_ip:389'
      });
    
      client.bind('cn=pratik', 'pratik', function(err) {
        if (err) return resp.send(err);
        var opts = {
          filter: '(objectclass=classToSearch)',
          scope: 'sub',
          attributes: ['ipaddress']
        };
        var entries = {};
        var i = 0;
        client.search('o=a', opts, function(err, res) {
          res.on('searchEntry', function(entry) {
            console.log('entry: ' + JSON.stringify(entry.object));
            oxe[i] = entry.object;
            i++;
          });
          res.on('end', function(result) {
            console.log("pratik");
            console.log(entries);
            return resp.send(entries);
          });
        });
      });
    });