简体   繁体   English

如何在Rails的响应主体之前发送响应头

[英]How can I send response headers before response body in Rails

Is it possible to generate response headers and send them back to the client without the body? 是否可以生成响应头并将其发送到没有主体的客户端?

send_headers
do stuff
render body

No, you cannot respond with headers to the client, perform an operation, and then respond with a body. 不可以,您不能使用对客户端的标头进行响应,执行操作然后使用正文进行响应。 (I'm not positive this is what you are asking) (我不是很肯定,这就是你要问的)

If you want to respond to the client and then perform some operation, you could use a background processor, like Sidekiq, to perform the logic after responding to the user but you won't be able to respond again with a body. 如果要响应客户端然后执行一些操作,则可以使用诸如Sidekiq之类的后台处理器在响应用户之后执行逻辑,但是您将无法再次以主体响应。

To answer the question directly, the headers are a part of the response, so unless you were sending a HEAD request which would only return the headers, you're stuck waiting for the entire response to come back. 为了直接回答这个问题,标头是响应的一部分 ,因此,除非您发送的是仅返回标头的HEAD请求 ,否则您将不得不等待整个响应返回。

To answer the question of long timeouts, there is a common pattern used for dealing with long requests which involves connection polling and the 202 Accepted response code. 为了回答长超时问题,有一个用于处理长请求的通用模式,该模式涉及连接轮询和202 Accepted响应代码。

You should engineer an endpoint solution that sends a 202 Accepted response straight away and sets the processing chain in motion. 应该工程师发送一个202接受响应直线距离 ,并设置运动中的处理链的端点溶液。 With that, you can create a resource which can give a useful estimate of how long the request will take, and where the result will be, and send that in the body of the response. 这样,您可以创建一个资源,该资源可以提供有关请求将花费多长时间以及结果将在何处的有用估计,并将其发送到响应的正文中。

Your ultimate goal should be to figure out why the request takes so long, but if it is ultimately designed to be a long and arduous response, either due to I/O or CPU time needed, or if it's a business requirement, then using 202 Accepted and setting up a form of connection polling would be your best option. 您的最终目标应该是弄清楚为什么需要这么长的时间,但是如果最终设计为响应时间长且费力(由于I / O或CPU时间的原因),或者如果是业务需求,则使用202接受并设置一种形式的连接轮询将是您的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM