ROR返回JSON,406不可接受错误

时间:2011-12-09 12:06:15

标签: ruby-on-rails

当我们使用render :json =>@profiles返回JSON输出时, 输出将返回所需的结果,并显示406错误。怎么能 避免'406 Not Acceptable'错误?

3 个答案:

答案 0 :(得分:13)

我非常确定你有this problem

说明:

假设您的控制器只返回json答案

def action
  # call
  respond_to do |format|
    format.json { render json: results }
  end
end

这将立即返回json:

  • /path_to_action.json被称为
  • 使用标题/path_to_action调用
  • Content-Type:application/json;,可能还有其他一些标题类型(例如X-Requested-With:XMLHttpRequest

否则,它会返回406 Not Acceptable错误。

为避免此问题,如果您的控制器只返回json,请写:

def action
  # call
  render json: results
end

否则,请改用/path_to_action.json

答案 1 :(得分:1)

只是扩大道格的答案,对于可能仍然迷惑这个问题的人,

当用于POST http请求的控制器方法呈现JSON而不是重定向时,也会更具体地发生此问题。如果此方法具有before_action,而before方法尝试“ redirect_to”而不是最初打算呈现JSON,则将弹出错误消息。

要解决此问题,只需确保您针对该方法的before_action也呈现了响应,而不是尝试重定向它。

示例:

before_action :require_configuration_training

def locations_post
  response = 'hey'
  render json: response, status: 200
end


def require_configuration_training
 response = 'hi'
 # Correct below:
 render json: response, status: 200

 # Wrong and will raise error below:
 # redirect_to another_path
end

答案 2 :(得分:0)

当我在控制器操作上有before_action :authenticate_user!但是从未经身份验证的页面调用它时,发生了这种情况。

页面本身正在尝试发出重定向。

对用户进行身份验证,或删除before_action为我解决了问题。