简体   繁体   English

法拉第可以访问请求参数

[英]Faraday get access to the request parameters

Struggling a bit with faraday. 挣扎与法拉第。 I would like to know what I actually send to the server. 我想知道我实际发送到服务器的内容。 I get the response body, but not access the request body. 我得到了响应正文,但没有访问请求正文。 I found that there is a request.env method, but I can't get access to the body there somehow. 我发现有一个request.env方法,但是我无法以某种方式访问​​那里的正文。

How would that work? 那将如何工作?

conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
  faraday.request  :url_encoded             # form-encode POST params
  faraday.response :logger                  # log requests to STDOUT
  faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
end

data = conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{ "name": "Unagi" }'
end

# how do I get access to the request body here?

What I tried doing was this: 我尝试做的是这样的:

[4] pry(main)> request.env.request

=> #<struct Faraday::RequestOptions
 params_encoder=nil,
 proxy=nil,
 bind=nil,
 timeout=nil,
 open_timeout=nil,
 boundary=nil,
 oauth=nil>

But I have no access to the body. 但是我无法进入身体。 Any ideas? 有任何想法吗?

Thanks! 谢谢!

You could try implementing a middleware just for this purpose. 您可以尝试为此目的实现中间件。 Just to give you a quick idea on what you can do to achieve this (there might be an easier way but I don't really know, I suppose because you specify the request body there's no real need to capture this as you should already have this available). 只是为了让您快速了解实现该目标的方法(可能有一种更简单的方法,但是我真的不知道,我想是因为您指定了请求正文,所以并没有真正的必要,因为您应该已经拥有了此可用)。

require 'faraday'

class RequestBody < Faraday::Middleware
  def call(env)
    request_body = env.body

    @app.call(env).on_complete do |response|
      response[:request_body] = request_body
    end
  end
end

conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
  faraday.use RequestBody
  faraday.adapter Faraday.default_adapter
end

data = conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.headers['foo'] = 'bar'
  req.body = '{ "name": "Unagi" }'
end

# 2.2.2 > data.env[:request_body]
#  => "{ \"name\": \"Unagi\" }"
# 2.2.2 > data.env.request_headers
#  => {"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/json", "foo"=>"bar"}
# 2.2.2 > data.body
#  => "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head><body>\n<h1>Moved Permanently</h1>\n<p>The document has moved <a href=\"http://www.sushi.com/index.php/nigiri\">here</a>.</p>\n<hr>\n<address>Apache/2.4.10 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 PHP/5.4.32 Server at sushi.com Port 80</address>\n</body></html>\n"

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

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