406 error when responding with json

前端 未结 1 1564
北恋
北恋 2021-02-14 11:02

I\'m trying to get a rails app running with the node.js framework batman.js via the batman-rails gem.

When I\'m responding with json in my rails controller, I get a 406

相关标签:
1条回答
  • 2021-02-14 11:26

    Alright, I made a very simple app to check out your situation:

    SamplesController.rb

    class SamplesController < ApplicationController
      respond_to :json
    
      def show
        respond_with Sample.find(params[:id])
      end
    
      def index
        respond_with Sample.all
      end
    end
    

    When I visited /samples.json and samples/1.json, it worked as intended. However, when I went to /samples and /samples/1 (no .json extension), I got a 406 error.

    In order to have the URL's work without the .json extension, you need to modify your config/routes.rb file as follows:

    resources :samples, defaults: {format: :json}
    

    Otherwise, the Rails application will attempt to respond to the request with an HTML response.

    0 讨论(0)
提交回复
热议问题