用json响应时出错406错误

我正试图通过batman-rails gem获得一个使用node.js框架batman.js运行的rails应用程序。

当我在我的rails控制器中使用json进行响应时,每次都会出现406错误,我不知道为什么。 这是我的控制器:

respond_to :json def index respond_with Sample.all end 

无论如何,这给了我406。 我不认为这与蝙蝠侠有关,而是跟踪自己。 但是好的方法,这是我的蝙蝠侠代码:

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

然后我的index.html.erb文件简单地说’index’,它实际上并没有用蝙蝠侠做任何事情。

有很多与406 JSON相关的问题,我还没有真正将它们应用到我的情况中。 有没有什么我做错了让rails response_with JSON?

好吧,我做了一个非常简单的应用程序来检查你的情况:

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 

当我访问/samples.jsonsamples/1.json ,它按预期工作。 但是,当我去/samples/samples/1 (没有.json扩展名)时,我得到了406错误。

为了使URL的工作没有config/routes.rb扩展名,您需要修改config/routes.rb文件,如下所示:

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

否则,Rails应用程序将尝试使用HTML响应来响应请求。

Interesting Posts