POST/Redirect/GET (PRG) vs. meaningful 2xx respons

2019-03-18 08:08发布

问题:

Since the POST request in a POST/Redirect/GET (PRG) pattern returns a redirect (303 See Other) status code on success, is it at all possible to inform the client of the specific flavour of success they are to enjoy (eg. OK, Created, Accepted, etc.) as well as any appropriate headers (eg. Location for a 201 Created, which might conflict with that of the redirect)?

Might it be appropriate, for example, to make the redirected GET respond with the proper response code & headers that would be expected from the POST response?

The HTTP 1.1 spec says:

This method [303] exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource.

But doesn't offer any insight into the loss of the more usual status code and headers.

Edit - An example:

A client sends POST request to /orders which creates a new resource at /orders/1.

If the server sends a 201 Created status with location: /orders/1, an automated client will be happy because it knows the resource was created, and it know where it is, but a human using a web browser will be unhappy, because they get the page /orders again, and if they refresh it they're going to send another order, which is unlikely to be what they want.

If the server sends a 303 See Other status with location: /orders/1 the human will be taken to their order, informed of its existence and state and will not be in danger of repeating it by accident. The automated client, though, won't be told explicitly of the resource's creation, it'll have to infer creation based on the location header. Furthermore, if the 303 redirects somewhere else (eg. /users/someusername/orders) the human may be well accomodated, but the automated client is left drastically uninformed.

My suggestion was to send 201 Created as the response to the redirected get request on the new resource, but the more I think about it, the less I like it (could be tricky to ensure only the creator receives the 201 and it shouldn't appear that the GET request created the resource).

What's the optimal response in this situation?

回答1:

Send human-targetted information in the response body as HTML. Don't differentiate on the User-Agent header; if you also need to send bodies to machines, differentiate based upon the Accept request header.



回答2:

If you have control over the web server, how about differentiating between the Agent header ? Fill it in something only you know of (a GUID or other pseudo-random thing) and present that one to the webserver from the automated client. Then have the webserver response with 201 / 303 accordingly.



标签: http