I will use the simple Sinatra application below to explain.
First, we run the app.
$ ruby app.rb
This launches a server at localhost:4567
.
- Open your browser at
http://localhost:4567
. - Enter your name, say Dwayne, and click Set.
- Doing so causes your browser to send a POST request to /set with name=Dwayne.
- The corresponding route handler then "sets a cookie" under the name name with value Dwayne.
- What really happens is that the Set-Cookie header is set with name=Dwayne.
- The redirect is executed causing a
303 status
and at least the Set-Cookie and Location headers to be sent to the browser. - The browser stores the cookie and will send it via the COOKIE header with any subsequent request, which happens to be now.
- You see, the 303 redirect causes the browser to immediately make another request to the URL given in the Location header, /. Hence, the cookie information will be sent along.
- The corresponding route handler then fetches the relevant cookie and displays the appropriate message.
References