406 error when responding with json

二次信任 提交于 2019-12-03 13:22:49

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!