Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why POST redirects to GET and PUT redirects to PUT?

I am using express 4.13.3 (latest) and following code:

var express = require('express')

var app = express()

app.get('/test', function (req, res, next) {
  res.send('hello!')
})

app.post('/test', function (req, res, next) {
  res.redirect('/test')
})

app.put('/test', function (req, res, next) {
  res.redirect('/test')
})

app.listen(5001)

// GET /test -> 'hello!'
// POST /test -> 'hello!'
// PUT /test -> ERR_TOO_MANY_REDIRECTS

POST redirects to GET but PUT redirects to PUT. Is it possible to make PUT redirect to GET (same as POST)?

like image 912
user606521 Avatar asked Oct 19 '15 12:10

user606521


People also ask

What is the reason that we consider the post redirect Get pattern best practice?

PRG is one of many design patterns used in web development. It is used to prevent the resubmission of a form caused by reloading the same web page after submitting the form. It removes redundancy of content to strengthen the SEO and makes the website user friendly.

Should you redirect after POST request?

The redirect is only for clearing all post data. If you choose not to redirect, the user can experience some inconvenience when he uses the back or forward buttons. He will be asked to send the post data again.

Is a redirect a post or get?

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.


1 Answers

Before diving in the details, below is one way of how you could solve the problem:

app.put('/test', function(req, res, next) {
    res.redirect(303, '/test') // Notice the 303 parameter
})

By default Express uses HTTP code 302 for the redirect. According to the HTTP specification, this prevents POST/PUT requests from being redirected as POST/PUT requests and explains what you observed in your code:

If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

On the other hand, if you use a 303 redirect, the POST/PUT request is allowed to be redirected as a POST/PUT request as explained in this great SO answer:

303: Redirect for undefined reason. Typically, 'Operation has completed, continue elsewhere.' Clients making subsequent requests for this resource should not use the new URI. Clients should follow the redirect for POST/PUT/DELETE requests.

like image 156
xaviert Avatar answered Oct 23 '22 21:10

xaviert