I'm specifying "json" in my render, but my content type returns as "text/html"

satish Source

I'm confused about why my "content-type" header is returning as "text/html". I have this method

  def work
    ...
    respond_to do |format|
      format.html {
        render json: Rails.cache.fetch(cache_key)
      }
    end
  end

When I invoke the URL "/work" in a Rails test and call

    get car_work_url, params: {worker_id: id}

    # Verify the response
    puts "response content type: #{response.content_type}"

It prints out as "text/html". Shouldn't it be "application/json" since I specified that in my "render"? Am I doing anything wrong or is this how its supposed to be?

ruby-on-railsresponserendercontent-type

Answers

answered 3 months ago Sergio Tulentsev #1

Shouldn't it be "application/json" since I specified that in my "render"?

Normally yes, but this time the render call is in a format.html block. This means that client requested html and whatever content comes out of rendering will be treated as html.

If you don't need this action to return html (this is an api endpoint, for example), you can drop the respond_to.

def work
  ...
  render json: Rails.cache.fetch(cache_key)
end

comments powered by Disqus