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.
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 .
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.
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])
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With