【问题标题】:Faraday middleware know when something was redirected法拉第中间件知道什么时候被重定向
【发布时间】:2015-06-22 09:09:45
【问题描述】:

我正在使用以下代码发出请求并遵循重定向:

require 'faraday'
require 'faraday_middleware'
conn = Faraday.new() do |f|
  f.use FaradayMiddleware::FollowRedirects, limit: 5
  f.adapter Faraday.default_adapter
end
resp = conn.get('http://www.example.com/redirect')
resp.status

此代码输出 200,因为它遵循重定向,这很棒。但是无论如何要知道重定向是否存在? resp.redirected 之类的东西,如果遵循了重定向,则设置为 true;如果没有遵循重定向,则设置为 false?

我在FollowRedirects 代码中没有看到任何明显的内容。

如果我想知道这一点,是否需要编写自己的自定义中间件?有谁知道可能已经这样做的中间件吗?

【问题讨论】:

  • 查看Typhoeus github.com/typhoeus/typhoeus,搜索followlocation。我不知道它是否符合您的要求,但它可能会。 :-) 您可能想要运行调试器并检查响应对象是否有任何提示。
  • 谢谢!我认为我拥有的代码正确地遵循了重定向。我感兴趣的是知道何时遵循重定向。我想我需要将生成的 url 与原始 url 进行比较,看看它们是否相同。我只是不知道法拉第响应中是否有最终网址。
  • 我知道,我只是想知道它是否有一些帮助方法来告诉你它是否被重定向。 :-)
  • 你确实激发了一些让我想到下面答案的东西,所以谢谢。

标签: ruby faraday


【解决方案1】:

我找到了解决方案。您可以将回调传递给FaradayMiddleware::FollowRedirects。回调应该存在于 FollowRedirects 采用第二个参数的哈希中。由于我们必须将 use 函数用于中间件,因此您可以将哈希值作为第二个参数传递给该函数。

  redirects_opts = {}

  # Callback function for FaradayMiddleware::FollowRedirects
  # will only be called if redirected to another url
  redirects_opts[:callback] = proc do |old_response, new_response|

    # you can pull the new redirected URL with this line of code.
    # since you have access to the new url you can make a variable or 
    # instance vairable to keep track of the current URL

    puts 'new url', new_response.url
  end

  @base_client = Faraday.new(url: url, ssl: { verify: true, verify_mode: 0 }) do |c|
    c.request :multipart
    c.request :url_encoded
    c.response :json, content_type: /\bjson$/
    c.use FaradayMiddleware::FollowRedirects, redirects_opts //<- pass hash here
    c.adapter Faraday.default_adapter
  end

【讨论】:

    【解决方案2】:

    其实,我想我只是根据这里的帖子找到了答案:https://stackoverflow.com/a/20818142/4701287

    我需要将我传入的原始 url 与生成的 url 进行比较。从上面扩展我的示例:

    original_url = 'http://www.example.com/redirect'
    resp = conn.get(original_url)
    was_redirected = (original_url == resp.to_hash[:url].to_s)
    

    【讨论】:

    • 对我来说,这个值总是 nil
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 2021-07-14
    • 2012-11-08
    相关资源
    最近更新 更多