lostisland / faraday

Simple, but flexible HTTP client library, with support for multiple backends.
https://lostisland.github.io/faraday
MIT License
5.76k stars 981 forks source link

Faraday doesn't return JSON response when upgrade to v2.10.11 #1591

Open minhtienvu opened 2 months ago

minhtienvu commented 2 months ago

Basic Info

Issue description

Steps to reproduce

This is my current code

client ||= Faraday.new(Settings.url) do |faraday|
  faraday.headers["X-Access-Key"] = access_key if access_key
  faraday.request :json
  faraday.response :json
end

client.post(
  Settings.url,
  {
    "name" => "John Doe",
  }.to_json
)

My Rails app used Faraday v0.9 very well and returned a response like this

{"reason"=>"invalid"}

But right now, with Faraday v2.10.1, it returns

"{\"reason\":\"invalid\"}"

Some ways I tried but didn't work:

  1. Change content-type
    client ||= Faraday.new(Settings.url) do |faraday|
    faraday.headers["X-Access-Key"] = access_key if access_key
    faraday.request :json
    faraday.response :json, content_type: /\bjson$/
    end
  2. Add a adapter
    client ||= Faraday.new(Settings.url) do |faraday|
    faraday.headers["X-Access-Key"] = access_key if access_key
    faraday.request :json
    faraday.response :json
    faraday.adapter :net_http
    end

CHECKLIST (delete before creating the issue)

olleolleolle commented 2 months ago

👋 Oh!

https://lostisland.github.io/faraday/#/middleware/included/json

The to_json should now be optional, since the request middleware part of the json middleware would make that attempt for you.

Is the server's response using a Content-Type that matches what json middleware wants to deal with?

There was a cool note here, that you can add a preserve_raw: true option, to see the unprocessed values Faraday got, as well, if you suspect something goes wrong in decoding: https://lostisland.github.io/faraday/#/middleware/included/json?id=json-responses

iMacTia commented 2 months ago

Adding to @olleolleolle comment, I'd also suggest to add the logger middleware and share the response logs with us, so we can see if there's anything weird with the response.

Please note by default the logger only logs the response headers, so make sure you pass the right options to it (and obviously redact any sensitive data before sharing them with us):

  faraday.response :logger, nil, { headers: true, bodies: true, errors: true }