簡體   English   中英

法拉第可以訪問請求參數

[英]Faraday get access to the request parameters

掙扎與法拉第。 我想知道我實際發送到服務器的內容。 我得到了響應正文,但沒有訪問請求正文。 我發現有一個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>

但是我無法進入身體。 有任何想法嗎?

謝謝!

您可以嘗試為此目的實現中間件。 只是為了讓您快速了解實現該目標的方法(可能有一種更簡單的方法,但是我真的不知道,我想是因為您指定了請求正文,所以並沒有真正的必要,因為您應該已經擁有了此可用)。

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