Redirecting with a 201 created

后端 未结 4 1854
无人及你
无人及你 2021-02-03 21:30

Is there a way to redirect through a 201 answer?

The RFC specifies that the newly created resource must be specified in the Location header, and I do specif

相关标签:
4条回答
  • 2021-02-03 22:13

    The browser will enact a redirect action through one of the 3xx status codes, the specification doesn't define that a user agent must redirect with a 201. You could try sending a refresh header to see if it forces a redirect to the Location header, but I wouldn't count on it. Why not stick with a 3xx response?

    0 讨论(0)
  • 2021-02-03 22:15

    You could send a Refresh header.

    0 讨论(0)
  • 2021-02-03 22:23

    I think you're confusing two different semantic responses - one is telling the client that you successfully created a resource, and where it is. Whether the client goes to fetch it or not is a different story.

    The second is telling the client that it has sent the wrong location URI for a resource it's requesting - and that it should try again, but with a different URI.

    A 303 is appropriate in this case - in fact, it's explicitly recommended for this:

    (from rfc)

    It is primarily used to allow the output of a POST action to redirect the user agent to a selected resource, since doing so provides the information corresponding to the POST response in a form that can be separately identified, bookmarked, and cached, independent of the original request.

    0 讨论(0)
  • 2021-02-03 22:25

    I am dealing with this for the first time, and this is what I have decided to do:

    • GET /user/new -> 200 Ok with user registration form.
    • POST /user -> 201 Created a new user, respond with the same content as the GET /user route.
    • GET /user -> 200 Ok with the user profile page for the authenticated user, or, for anonymous visitors, 307 Temporary Redirect to /login, which links to /user/new.

    update

    I have found out that this is a bad idea, because if the user refreshes the page that was rendered as a response for POST /user, they resend the post data. I will leave the answer here in case anyone else has the same brilliant idea.

    0 讨论(0)
提交回复
热议问题