curt curt - 1 year ago 75
JSON Question

Rails Not Recognizing JSON as Response Type

I'm working on infinite scroll on my Rails web site using Dart as the client side code. I found an example of a call and, amazingly, it worked the first time. The problem is that it's returning the same html as I would get if I clicked the next button. I don't need the entire page, just the scroll data. I decided to try to JSON. The request is processed by Rails, but it still renders it as html. This is the change I made:

html request


json request

HttpRequest.request(url, responseType: 'json').then(onDataLoaded);

The variable url has a copy of the url from the 'Next' button:


When I print to the browser console, using this response handler:

void onDataLoaded(HttpRequest resp) {

The status text is OK.
The response headers are:

{x-runtime: 0.049101, date: Thu, 09 Jun 2016 23:51:05 GMT, x-content-type-options: nosniff, server: Apache/2.4.18 (Unix) Phusion_Passenger/5.0.24 PHP/5.5.34, x-powered-by: Phusion Passenger 5.0.24, x-frame-options: SAMEORIGIN, content-type: text/html; charset=utf-8, status: 200 OK, cache-control: max-age=0, private, must-revalidate, transfer-encoding: chunked, etag: W/"fb290bd42f831f80ea9359040304ea39", connection: Keep-Alive, keep-alive: timeout=5, max=100, x-xss-protection: 1; mode=block, x-request-id: 9921c6c7-2fb6-43b9-89d3-636fb4a3aec0}

The rest.response is null.

I checked the network data in the Chrome browser and saw the full html data on the response tab. The Dart code must think it's json and can't display it

Here's the Rails application log from a json response type request:

Started GET "/artists?page=2" for at 2016-06-10 17:05:06 -0700
Processing by ArtistsController#index as */*
Parameters: {"page"=>"2"}
ArtistsController index method
Rendered artists/_list_subnav.html.erb (0.2ms)
Artist Load (1.3ms) SELECT `artists`.* FROM `artists` ORDER BY last_name, first_name LIMIT 25 OFFSET 25
(0.4ms) SELECT COUNT(*) FROM `artists`
Rendered artists/index.html.erb within layouts/application (22.9ms)
Completed 200 OK in 31ms (Views: 28.6ms | ActiveRecord: 1.7ms)

I have a index.json.erb and I also tried adding this to the controller:

def index
# Perform any filtering using ransack search
logger.debug "ArtistsController index method format"
@q =[:q])
# Partition the output using kaminari page
@artists = @q.result.order('last_name', 'first_name').page(params[:page])
respond_to do |format|
format.json { render :json => @artists }

How do I get Rails to render json? How is format set in the code above?


I've completely rewritten the question.

Answer Source

It took two days of digging to find it. You need to add an Accept header to the request. Here's how I fixed my problem above:

Map headers = {'Accept': 'application/json'};
HttpRequest.request(url, requestHeaders: headers).then(onDataLoaded);