在法拉第中苦苦挣扎。我想知道我实际发送到服务器的内容。我得到了响应正文,但没有访问请求正文。我发现有一种request.env
方法,但我无法以某种方式访问那里的身体。
那会怎么样?
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?
我尝试做的是:
[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>
但我无法进入尸体。有什么想法吗?
谢谢!
答案 0 :(得分:4)
您可以尝试为此目的实现中间件。只是为了让你快速了解你可以做些什么来实现这个目标(可能有一种更简单的方法,但我真的不知道,我想因为你指定了请求体,所以没有真正需要捕获它,因为你应该已经拥有这个可用)。
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"