Sunday, 12 March 2017

Why does my express router crash only when i send a JSON and not when i send a text ?

statusRouter.route('/')
.all(function(req,res,next){
  res.writeHead(200, {'Content-Type': 'application/json'});
  next();
})
.get(function(req, res, next) {
    res.json({
       name : "xyz"
     });
});

This crashes with - Header cant be set after it has been sent.
But the catch is , this works :

statusRouter.route('/')
.all(function(req,res,next){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  next();
})
.get(function(req, res, next) {
    res.end("xyz");
});

NOTE : If I remove the writeHead function in the first case where I am sending JSON it starts working as well. Why does it not work when i do a writeHead on it ? This thing is driving me crazy can anyone explain why this happens ?
P.S I'm working with express-generated app with my own router.



via Pavan

No comments:

Post a Comment