Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

res.send and res.render calls

I am trying to determine if i can call res.send(data) and then res.render('reports') simultaneously.

To explain further in detail, when i route to '/reports', first on my server side i making a REST call to an API which returns back json data. Now i want this json data to be accessed on the client, for which i am making an ajax call from my javascript. Hence the use of res.send(), but i also want to render the page in this call

So it looks like the following on my server side code

router.get('/reports', function(req,res){
     //Making the REST Call to get the json data
     //then
     res.send(json);
     res.render('reports');
});

Every time i hit the '/reports' on the browser, I see the json value instead of the page being rendered and my console throws an Error: Can't set headers after they are sent.

like image 894
Raj Avatar asked Jun 15 '15 13:06

Raj


People also ask

Can you do Res send and res render?

No, you can't. You can only have a single response to a given request. The browser is either expecting an HTML document or it is expecting JSON, it doesn't make sense to give it both at once. render just renders a view and then calls send .

What is the difference between Res send and RES status?

The res object basically refers to the response that'll be sent out as part of this API call. The res. send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.

What does res render mean?

The res. render() function is used to render a view and sends the rendered HTML string to the client. Syntax: res.render(view [, locals] [, callback])

Does Res send call res end?

res. send() is used to send the response to the client where res. end() is used to end the response you are sending. Save this answer.


1 Answers

You could use content negotiation for that, where your AJAX request sets the Accept header to tell your Express server to return JSON instead of HTML:

router.get('/reports', function(req,res) {
  ...
  if (req.accepts('json')) {
    return res.send(theData);
  } else {
    return res.render('reports', ...);
  };
});

Alternatively, you can check if the request was made with an AJAX call using req.xhr (although that's not 100% failsafe).

like image 114
robertklep Avatar answered Oct 22 '22 15:10

robertklep