HTTP response with redirect, but without roundtrip

2019-02-18 04:38发布

问题:

I want the browser to reflect some other URL than the one used to create the request, but without roundtripping to the server.

I would maybe do this:

POST /form HTTP/1.1
...

...and then return:

HTTP/1.1 200 OK
Location: /hello

But that would cause a redirect, the browser will again, request URL /hello.

I would like to just tell the browser that, while the request you just sent was POST /some_url the actuall resource that I'm now returning is actually called GET /hello/1 but without preforming a roundtrip. i.e. Location: ...

Is there any way to do this with JavaScript or the base="" attribute? That will tell the browser to request /hello/1 when I hit F5 (refresh) instead of that, post submission warning?

回答1:

HTTP/1.1 200 OK
Location: /hello

Actually that probably wouldn't work; it should be a 30x status rather than 200 (“303 See Other” is best for the response to a POST), and ‘Location’ should be a complete absolute URL.

(If your script just says ‘Location: /relativeurl’ without the 30x status, CGI servers will usually do an internal redirect by fetching the new URL and returning it without telling the browser anything funny happened. This may sound like what you want but it isn't really because from the browser's point of view it's no different from the original script returning a 200 and direct page.)

But that would cause a redirect, the browser will again, request URL /hello.

In practice that's probably not as bad as you think, thanks to HTTP/1.1 keep-alives. The client should be able to respond to the redirect straight away (in the next packet) as long as it's on the same server.

Is there any way [...] That will tell the browser to request /hello/1 when I hit F5 (refresh) instead of that, post submission warning?

Nope. Stick with the POST-Redirect-GET model for solving this.



回答2:

No. Http is stateless, and every request has one answer. When you post, you need to redirect to a get page immediately to prevent a double post - you don't want it to sit on that post url. The redirect is what tells the browser that it is on a new page. That's just the way it works.



标签: http redirect