I’m currently following the Pluralsight training Full Stack Node.js. The course was release more than a year ago and it is based on express.js 2.x.
I have chosen to build the course sample on express 3.x and because of this some features described on the course are no more applicable.
The purpose of this blog post is to actually demonstrate how to migrate properly one of the them: “The Flashing”.
Simply put, the flashing consist of displaying a status message once an operation executed on a post has completed.
The Flashing is particularly useful when using the Post/Redirect/Get Pattern. The all scenario can be described as:
- The user submit a form with a POST action
- The user form is process and a result status is generated such as “Error” or “Success”
- The Post action completes with a redirect that will tell the client browser to GET another page.
- The rendering of the get result should display the processing status
I found several questions on stackexchange explaining how to do that but none of them was clear enough for me to understand…
So I digged a bit and I decide to share my findings here.
The original solution was using app.dynamicHelpers which is not applicable anymore.
The migration document from express 2.x to 3.x just says replace with:
middleware and res.locals…
Fine… How am I suppose to do that? Well I believe the answer is incomplete.
You will use the middleware to add processing into the handling of your request and its response.
After all this is why the middleware is there for. Then in the middleware you will attach a function that can be used in the route handler.
This function will use res.locals to attach something to your response that can be used on the rendering of the view. This is incomplete…
or at least this how I understood it and it felt incomplete.
Our problem here is that we are using the Post/Redirect/Pattern and this means that all data attach to the res.locals vanish as soon as you do a redirect.
The redirect will instruct the browser to perform a GET and this will start the request from the processing of the HTTP request from the beginning.
There is no way to solve our issue just with a middleware and res.locals!!! We need a way to pass information from the POST and REDIRECT to the following GET.
The only to do this is via a cookie or in the session. But those will then need to be cleaned once the status message has been displayed.
This is how I have achieved this. First I have implemented the middleware and it looks like this:
|
|
The middleware will need to be added to your app express instance as usual.
|
|
Then from the route handler of the POST processing we have the following implementation.
This is basically where we set the status of the processing.
|
|
And finally we can use the status information that will have been attached to the res.locals from the jade template
|
|