使用post方法和params将用户重定向到外部URL

问题描述:

如何通过post方法将用户重定向到外部网址?我知道 redirect_to 仅适用于 get 请求。我如何实现这一目标?

How do i redirect user to external url via post method? I know redirect_to works only for get requests. How do i achieve this?

您无法将用户重定向到 POST 方法。您可以向用户显示Rails JS将转换为表单/ POST的链接:

You cannot redirect a user to a POST method. You can present a user with a link that the Rails JS will turn into a form/POST:

= link_to "Do it!", "http://other.site/path", method: :post

...或者一个触发 POST 到另一个网站的表格(注意我已经包含了一个额外的参数),例如。

...or a form that triggers a POST to another site (note that I've included an extra param in this) eg.

= form_tag "http://other.site/path", method: :post do
  = hidden_field_tag :foo, "Bar"
  = submit_tag "Do it!"

...或者您可以代表您的用户从服务器端自行提出请求(此处为我正在使用 httparty gem),请注意我包含相同的 foo = Bar 参数:

...or you can make the request yourself from the server side on your user's behalf (here I'm using the httparty gem), note that I'm including the same foo=Bar parameters:

class YourController < ApplicationController
  include HTTParty

  def some_action
    self.class.post "http://other.site/path", query: { foo: "Bar" }
  end
end

为您提供几种选择。