Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the "post/redirect/get" pattern

I am having a very hard time understanding the exact process of "post/redirect/get".

I have combed through this site and the web for several hours and cannot find anything other than "here's the concept".

How to understand the post/redirect/get pattern?

like image 264
whatdafrak Avatar asked May 31 '12 03:05

whatdafrak


People also ask

Is redirect a GET or POST?

POST: A form is sent to the server with a post-request and an entry in the database is changed. Redirect: After a post request, the correct webpage with the changed data is delivered to the client using the redirect instruction (HTTP 303). GET: The client requests a confirmation page.

Is redirect always a get?

A redirect is an Http response sent to the client. The response contains an Http Header called Location which must contain an absolute url. The client then issues a GET request against this url. So, no, POST is not an option.

How does HTTP POST redirect work?

In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3 , and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header.


2 Answers

Wikipedia explains this so well!

The Problem

The Problem

The Solution

The Solution

like image 195
MasterMastic Avatar answered Oct 19 '22 23:10

MasterMastic


As you may know from your research, POST-redirect-GET looks like this:

  • The client gets a page with a form.
  • The form POSTs to the server.
  • The server performs the action, and then redirects to another page.
  • The client follows the redirect.

For example, say we have this structure of the website:

  • /posts (shows a list of posts and a link to "add post")
    • /<id> (view a particular post)
    • /create (if requested with the GET method, returns a form posting to itself; if it's a POST request, creates the post and redirects to the /<id> endpoint)

/posts itself isn't really relevant to this particular pattern, so I'll leave it out.

/posts/<id> might be implemented like this:

  • Find the post with that ID in the database.
  • Render a template with the content of that post.

/posts/create might be implemented like this:

  • If the request is a GET request:
    • Show an empty form with the target set to itself and the method set to POST.
  • If the request is a POST request:
    • Validate the fields.
    • If there are invalid fields, show the form again with errors indicated.
    • Otherwise, if all fields are valid:
      • Add the post to the database.
      • Redirect to /posts/<id> (where <id> is returned from the call to the database)
like image 43
icktoofay Avatar answered Oct 19 '22 23:10

icktoofay