ruby 法拉第Response不是JSON

j1dl9f46  于 2023-06-05  发布在  Ruby
关注(0)|答案(1)|浏览(254)

在Ruby 3.1.3和Faraday 2.7.5中,我永远无法从法拉第获得JSON响应:

def connection
      @connection ||= Faraday.new(
        url: url,
        headers: headers
      ) do |faraday|
        faraday.response :json
        faraday.request :json
      end
    end

    def headers
      { content_type: 'application/json',
        accept: 'application/json' }
    end

    def send_request
      connection.send(method) do |req|
        req.body = body
      end
    end

运行时,我检查了response.body,它从来不是JSON(即使我有faraday.response :json

[1] pry(#<App>)> response.body
=> "{\"data\":{\"date\":\"some_data\"}}"

我必须:

[2] pry(#<>)> JSON.parse response.body
=> {"data"=>{"date"=>"some_data"}}

我正在检查的测试是:

let(:response_body) { { data: { date: 'some_data' } }.to_json }
 
 ...

stub_request(:post, url)
  .with(
     body: body.to_json,
     headers: custom_headers
   ).to_return(status: status, body: response_body, headers: {})
end

it 'POSTS to a url' do
  subject
  expect(a_request(:post, url)).to have_been_made
 end
end

是我的测试出错了,还是客户端代码总是返回json出错了?

brqmpdu1

brqmpdu11#

我的猜测是你请求的API没有设置正确的content-type响应头。
我没有深入研究法拉第代码,但似乎如果响应不是'application/json'格式,response.body将以普通字符串形式交付。

conn = Faraday.new do |f|
   f.request :json 
   f.response :json
end

res = conn.get("https://dummyjson.com/products/1")
res.body["id"]
# => 1

res.body.class
# => Hash

res.headers["content-type"]
# => "application/json; charset=utf-8"

res = conn.get("https://example.com")
res.headers["content-type"]
# => "text/html; charset=UTF-8"

res.body[0, 80]
# => "<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta chars"

res.body.class
# => String

相关问题