如何在Her中向请求添加标头?



我正在使用Her与我制作的API对话,以便我可以从中检索信息。我需要一个通过报头传入的授权令牌。我该怎么做呢?文档没有显示任何解决方案,但它似乎是一个非常需要的实用程序。

@sethetter的评论基本上涵盖了它,但由于我最近做了类似的事情,我想我应该包括一些代码,有人可能会发现将来有用。因此,要做到这一点,您需要创建一个请求中间件,它在call方法中添加所需的标头。我必须做一些类似的事情,结果如下所示:

class Authentication < Faraday::Middleware
  def call(env)
    env[:request_headers]['auth-token'] = generate_token(env)
    @app.call(env)
  end
  def generate_token(env)
    # generate the token based on the request, if needed
  end
end

然后,当你构造API堆栈时:

require 'authentication' #if you've defined it in a different file
@api = Her::API.new
@api.setup(:url => my_api_base_url) do |c|
    c.use Authentication
    # other middlewares as usual
end

最新更新