简体   繁体   中英

Rails 4 - Respond only to JSON and not HTML

I'm trying to build an API in rails 4, and am having an issue where rails returns a 500 error instead of a 406 when using respond_to :json and trying to access the html version.

Here's an example controller demonstrating the problem:

class PostsController < ApplicationController
  respond_to :json

  def index
    @posts = Post.all
  end
end

I also have a jbuilder view for index that works when accessing via JSON. If I try accessing the route without the JSON extension, It attempts to load the HTML template (which doesn't exist) and returns a 500 error, instead of just rendering JSON or returning a 406 error.

What could be causing this? Cheers for any help.

I believe there are 2 parts here:
1) json only requests in rails
2) json only responses in rails

1) Configure your application controller to ensure json requests only

# app/controller/application_controller.rb  
before_action :ensure_json_request  

def ensure_json_request  
  return if request.format == :json
  render :nothing => true, :status => 406  
end  

2) Configure your Rails API routes to ensure json responses only

# config/routes.rb  
MyApp::Application.routes.draw do  
  namespace :api, constraints: { format: 'json' } do  
    namespace :v1 do  
      resources :posts  
    end  
  end  
end  

为避免加载不存在的 HTML 模板,请在 config/routes.rb 中将默认资源类型设置为 JSON:

resources :posts, :defaults => { :format => :json }

In Rails 4, you need to pass a lambda to enforce the constraint on a route.

Unfortunately, this will NOT work because it will still try to serve up (or attempt to serve up) an html template since the format is an optional parameter:

resources :posts, constraints: { format: 'json' }

This DOES work (uses the lambda):

resources :posts, constraints: lambda { |req| req.format == :json }

See the second (final) note in this section of the Rails guide .

As you are using a before_filter, you will have a 406 Not Acceptable if a request for a format is made which is not defined.

Example:

class SomeController < ApplicationController
  respond_to :json


  def show
    @record = Record.find params[:id]

    respond_with @record
  end
end

The other way would be to add a before_filter to check for the format and react accordingly.

Example:

class ApplicationController < ActionController::Base
  before_filter :check_format


  def check_format
    render :nothing => true, :status => 406 unless params[:format] == 'json'
  end
end

But i think, you can just do it:

respond_to do |format|
  format.json { render :json => @posts }
end

Further informations: http://guides.rubyonrails.org/layouts_and_rendering.html

constraints was not working for POST requests and then I tried defaults it works for all.

namespace :api, :defaults => { :format => 'json' } do
    namespace :v1 do
      resources :users do
        collection do
          get 'profile'
        end
      end
      post 'signup' => 'users#create'
      post 'login' => 'user_sessions#create'
  end
end

You can try this, as I was also facing this issue and now it is solved by using this solution.

class PostsController < ApplicationController
  respond_to :json

  def index
    @posts = Post.all
    render json: @posts
  end
end

您可以通过使用 before 过滤器将请求显式设置为 JSON 来设置它。

request.format = :json

when you try a responses in json is beacuse you only need some properties i used this

@my_model=Model.select(:attributeN, :attributeN......, attributeN)
respond_to do |format|
  format.json {
    render json: @my_model
  }
end

I would suggest you to try gem 'active_model_serializers' . Its really awesome and keeps clean.

ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception, if: Proc.new { |c| c.request.format != 'application/json' }
  protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }
end

Routes:

namespace :api, defaults: { format: :json } do
    resource :posts
end

Posts Controller:

def index
   render json: Post.all
end

I'm a bit late to this but regarding your comment to this answer :

I want all responses to be JSON

The easiest solution would be:

respond_to do |format|
  format.all { render :json => @posts }
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM