'Can’t set headers after they are sent. ' Express.js

Asked

Viewed 1,379 times

0

I’m trying to send the variable 'name' 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);
    }
  });
});

1 answer

1


This error consists because you are trying to send twice information to the customer as a response.

After responding to the customer’s header HEADER is sent... cannot overwrite or send another.

If you are "listening" to the answer and wish to receive one JSON, only reply in format JSON:

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 trying to "merge" this JSON and return a fragment HTML should do this before the answer possibly a "parse", "replace" or some function of your rendering framework and then return only with:

res.render(seu_fragmento_aqui)
  • In case I could not use both? The two I say the two res.

  • In case, I’m trying to send the variable and render!

  • This is not possible! After using one or the other you will be sending a reply, it is not possible to send two reply to the same request!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.