406 error when responding with json

◇◆丶佛笑我妖孽 提交于 2019-12-04 20:27:29

问题


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 error everytime, and I don't know why. Here's my controller:

  respond_to :json

  def index
    respond_with Sample.all
  end

This gives me a 406 no matter what. I do not think this is related to batman, but rails itself. But for good measure, here's my batman code:

  index: (params) ->
    TopNavTemplate.Sample.load (err) -> throw err if err
    @set 'samples', TopNavTemplate.Sample.get('all')

And then my index.html.erb file simply says 'index', it isn't really doing anything with batman yet.

There is a lot of 406 JSON related questions, I haven't really been able to apply them yet to my situation. Is there something I'm doing wrong to make rails respond_with JSON?


回答1:


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.



来源:https://stackoverflow.com/questions/12320259/406-error-when-responding-with-json

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