JSON响应时出现406错误 [英] 406 error when responding with json

查看:108
本文介绍了JSON响应时出现406错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图通过batman-rails gem与node.js框架batman.js一起运行Rails应用程序.

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

当我在Rails控制器中响应json时,每次都会收到406错误,我也不知道为什么.这是我的控制器:

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

无论如何,这都会给我406.我认为这与蝙蝠侠无关,但与护栏本身有关.但是,出于良好的考虑,这是我的蝙蝠侠代码:

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')

然后我的index.html.erb文件只是说'index',它实际上还没有对蝙蝠侠做任何事情.

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

有很多406个与JSON相关的问题,我还不能真正将它们应用于我的情况.使Rails使用JSON响应时我做错了吗?

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?

推荐答案

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

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

SamplesController.rb

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错误.

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.

为了使URL在不带.json扩展名的情况下工作,您需要按以下步骤修改config/routes.rb文件:

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}

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

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

这篇关于JSON响应时出现406错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆