Saturday, April 4, 2020

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



Error Blog 

This blog is about the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Problem Statement

unable to start node js express application

Error Details 

error Log

ERROR DETAILS 

\node_modules\mysql\lib\protocol\Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\express\lib\response.js:267:15)
    at F:\ \study\gitRepo\new\learn\nodejs\expressjs\service\users.js:24:11
    at Query.<anonymous> (F:\ \study\gitRepo\new\learn\nodejs\expressjs\service\task.service.js:20:21)
    at Query.<anonymous> (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\mysql\lib\Connection.js:526:10)
    at Query._callback (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\mysql\lib\Connection.js:488:16)
    at Query.Sequence.end (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
    at Query._handleFinalResultPacket (F:\ \study\gitRepo\new\learn\nodejs\expressjs\node_modules\mysql\lib\protocol\sequences\Query.js:149:8)




Error Code 

You will face this error if you res.send twice in an express js application.




var express = require('express');
var router = express.Router();
var Task = require('./task.service.js');

router.get('/'function(reqres){
   Task.getAllTask(function(errtask) {

      console.log('controller')
      if (err)
        res.send(err);
        console.log('res'task);
      res.send(task);
    });
});
router.post('/create'function(reqres){
   console.log(req.body);
   var new_task = new Task(req.body);
   console.log(new_task);
   Task.createTask(new_taskfunction(errtask) {
    
      if (err)
        res.send(err);
      res.json(task);
    });
   res.send('success.');

});

//export this router to use in our index.js
module.exports = router;



  

Solution

change the code so that res.send is not called twice . .

Code Changes 

add the following import in your component.ts file .

  
        
      if (err)
        res.send(err);
      res.json(task);
    });
  // res.send('success.');

         

OUTPUT
works 



Thanks for reading . Let me know your thoughts in the comments below    .

No comments:

Post a Comment

ec2-user@ec2 Permission denied