'Can not set headers after they are sent.' Express.js

0

I'm trying to send the 'name' variable to the client side, but it's only working when I run a respons.end() when I use two, returns this error:

> 'Can't set headers after they are sent.'

Server

router.get('/:eventnick', function(req, res, next){
  EventData.findOne({eventnick: req.params.username}, function(err, eventInfos){
    var name = eventInfos.name;//0
    res.render('event/eventpage/eventpage', {title: 'teste| '+ name},);
    res.end(JSON.stringify(name));
  });
});

Client

$(document).ready(function(){
  var url = window.location.href;
  var splitUrl = url.split('/');
  $.ajax({
    type: 'GET',
    url:'/event/'+splitUrl[4],
    success: function(data){
      console.log(data);
    }
  });
});
    
asked by anonymous 14.01.2018 / 18:26

1 answer

1

This error is because you are trying twice to send information to the client as a response.

After replying to the client the HEADER header is sent ... it is not possible to overwrite or send another one.

If you are "listening" to the answer and want to receive JSON , just reply in JSON format:

Server :

router.get('/:eventnick', function(req, res, next){
    EventData.findOne({eventnick: req.params.username}, function(err, eventInfos){
        var name = eventInfos.name;//0
        res.json(JSON.stringify(name));
    });
});

If you are attempting to "merge" this JSON and return a HTML snippet, you should do this before answering possibly a "parse", "replace" or some function of your rendering framework and then return only with:

res.render(seu_fragmento_aqui)
    
14.01.2018 / 20:00