如果部分响应已发送(分块),如何将浏览器发送到错误页面

发布于 2024-12-05 22:51:00 字数 693 浏览 1 评论 0原文

这是典型的场景:评估页面,并且有一个缓冲区 - 一旦缓冲区已满,评估的页面部分就会发送到浏览器。这使用 HTTP 1.1 分块编码。

但是,其中一个块中可能会出现错误(在第一个块已发送之后)。在这种情况下:

  • 您无法重定向(发送 Location 标头),因为标头和响应状态已发送
  • 您无法进行服务器端重定向(转发),因为新页面必须在已经发送的部分之后渲染 - 它肯定看起来很难看。

那么在这种情况下你应该做什么呢?我问了一个问题是否可以在分块预告片中发送 Location 标头,但这是低级 http,语言的抽象可能不允许这样做,即使这是可能的(并且可能不支持跨浏览器)

另一种选择是发送一个 从而强制客户端重定向,但这很丑陋。另外,您必须放置 来关闭部分页面中任何潜在的未关闭

(我标记了主要的网络语言/框架,因为这是一个普遍的问题)

This is typical scenario: a page is evaluated, and there's a buffer - once the buffer is full, the part of the page that is evaluated is sent to the browser. This uses the HTTP 1.1 chunked encoding.

However, an error can occur in one of the chunks (after the first one is already sent). In that case:

  • you can't redirect (send a Location header), because the headers and the response status were already sent
  • you can't do server-side redirect (forward), because the new page will have to be rendered after the part that is already sent - it will look ugly for sure.

So what should you do in this case? I asked a question whether you can send a Location header in the chunked trailer, but this is low-level http and the abstraction of languages may not allow it, even if it is possible (and it is likely not to be supported across browsers)

Another option is to send a <script>window.href.location="errorPage"</script> and thus force the client to redirect, but that's ugly. Plus you have to put </script> to close any potential unclosed <script> tag in the partial page.

(I'm tagging major web languages/frameworks, because this is an universal issue)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忘羡 2024-12-12 22:51:00

您无法以分块编码从服务器重定向,因为标头已经发送。执行重定向的唯一方法是从服务器发送

You cannot redirect from the server in a chunked encoding because the headers have already been sent. The only way to perform a redirect is to send a <script> tag from the server and perform a client side redirect. Just out of curiosity are you trying to implement a COMET server? If this is the case HTML5 WebSockets seem better way (if the browsers you are targeting support them of course) compared to the hidden iframe technique.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文