Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render multiple times on the same response object with ExpressJS?

I have a situation where I need multiple renders to occur with the same response object in an ExpressJS application. (Basically one HTTP request triggers multiple back-end requests, all of which can begin rendering results to the page immediately as they complete.) The problem is that I need each one to render a view (i.e. I don't think I can use res.write()), and as far as I can tell, there is no way for res.render() to not end the response or write headers each time it is called.

What am I missing?

like image 476
Chris Hart Avatar asked Dec 22 '11 17:12

Chris Hart


People also ask

What is the difference between response send() and response write() in Express?

response. send() sends the response and closes the connection, whereas with response. write() you can send multiple responses. In this article, I will explain the difference between response.

What does res render () function do?

The res. render() function is used to render a view and sends the rendered HTML string to the client.

What is RES locals in Express?

The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.


1 Answers

Express compiles the template using an engine like EJS, Jade etc.

The data is then rendered using response.send: https://github.com/visionmedia/express/blob/master/lib/response.js#L76-131

As you can see there, at the end there is this.end..., which means response.end(...).

If you want do achieve sending multiple views, you must compile those views yourself using the view engine and then create a function similar to response.send (which I gave you the link above), but be careful not to send the headers twice or call response.end before the last view is rendered.

like image 164
alessioalex Avatar answered Oct 16 '22 22:10

alessioalex