如何使redirect_to使用不同的HTTP请求?
在我的控制器操作之一结束时,我需要重定向到仅接受放置请求的页面。 我一直在尝试找出如何让redirect_to 使用 put 请求,但没有成功。
这可能吗? 或者还有其他方法可以实现此目的吗?
At the end of one of my controller actions I need to redirect to a page that only accepts put requests. I have been trying to figure out how to get redirect_to to use a put request but to no success.
Is this possible? Or is there another way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不认为你能够做到这一点,并且我怀疑该限制是 HTTP 本身的一部分。
使用 redirect_to 时 - 除非参数中另有指定,否则重定向将作为“302 Moved”标头发生。
查看 HTTP 规范本身并没有揭示任何更改浏览器通过重定向发出的请求类型的方法。
HTTP 重定向:
我认为您可能需要使用 JavaScript 来实现此功能,或者重新考虑应用程序中的控制流。
I don't think you are able to do this, and I suspect that the limitation is part of HTTP itself.
When using redirect_to - the redirection happens as a "302 Moved" header unless otherwise specified in the parameters.
Having a look at the HTTP Spec itself doesn't reveal any way to change the type of request the browser makes via redirect.
HTTP Redirects:
I think you may need to use JavaScript to achieve this functionality, or perhaps rethink the flow of control in your application.
如果该操作与您尝试重定向的位置位于同一控制器中,只需调用该操作并呈现模板,如下所示:
如果不是,那么我不知道您是如何做到这一点的。
If the action is in the same controller as where you're trying to redirect from, simply call the action and render the template like so:
If it's not, then I don't know how you do that.
好的,所以我找到了解决我的问题的方法。 我在此处找到了一篇关于这种情况的非常好的文章。 我的实现如下所示:
然后我这样调用这个方法:
因此,我能够通过发出 post 请求(使用
redirect_post
)来“伪造” put 请求,然后将“put”分配给 <代码>_method 参数。 如果你看一下正常的put
请求,它都是来自带有_method
参数的表单的post
。 所以它有点黑客,但它完成了工作。另外,您必须确保当您调用
redirect_post
时,哈希值是字符串,否则将引发错误。Ok, so I found a solution to my problem. I found a very good write up on the situation here. My implementation looks like this:
Then I called this method like this:
So I was able to 'fake' a put request by making a post request (using
redirect_post
) and then assigning 'put' to a_method
param. If you look at a normalput
request all it is apost
from a form with a_method
param. So its a bit hackish but it gets the job done.Also, you have to make sure that when you call
redirect_post
the values of your hash are strings otherwise errors will be thrown.您可以重定向到从客户端发出放置请求的不同页面, 使用 Javascript。
You could redirect to a different page that issues the put request from the client, using Javascript.