Rails 4 - Respond only to JSON and not HTML

前端 未结 10 1164
栀梦
栀梦 2020-12-08 02:59

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

相关标签:
10条回答
  • 2020-12-08 03:12

    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  
    
    0 讨论(0)
  • 2020-12-08 03:13

    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
    
    0 讨论(0)
  • 2020-12-08 03:15

    To avoid loading the non-existent HTML template, set the default resource type as JSON in config/routes.rb:

    resources :posts, :defaults => { :format => :json }
    
    0 讨论(0)
  • 2020-12-08 03:15

    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
    
    0 讨论(0)
  • 2020-12-08 03:16

    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
    
    0 讨论(0)
  • 2020-12-08 03:20

    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
    
    0 讨论(0)
提交回复
热议问题