Ruby on rails ROR返回JSON,错误为406不可接受

Ruby on rails ROR返回JSON,错误为406不可接受,ruby-on-rails,Ruby On Rails,当我们使用render:JSON=>@profiles返回JSON输出时 输出将返回所需的结果,并返回406错误。怎么可能 避免“406不可接受”错误 我非常肯定你有 说明: 假设您的控制器只返回json答案 def action # call respond_to do |format| format.json { render json: results } end end 这将在以下情况下尽快返回json: 调用/path\u to\u action.json /p

当我们使用
render:JSON=>@profiles
返回JSON输出时 输出将返回所需的结果,并返回406错误。怎么可能
避免“406不可接受”错误

我非常肯定你有

说明:

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

def action
  # call
  respond_to do |format|
    format.json { render json: results }
  end
end
这将在以下情况下尽快返回json:

  • 调用
    /path\u to\u action.json
  • /path\u to\u action
    通过标题调用
    内容类型:application/json
    和其他一些头类型(例如
    X-request-With:XMLHttpRequest
否则,它将返回一个
406不可接受的
错误

为避免此问题,如果控制器仅返回json,请编写:

def action
  # call
  render json: results
end

否则,请改用
/path\u to\u action.json

当我在\u action:authenticate\u user之前有
时,这种情况发生在我身上,但正在从未经验证的页面调用此操作

页面本身正试图发出重定向


对用户进行身份验证,或在\u操作之前删除
为我解决了问题

为了进一步阐述道格的答案,无论是谁,可能仍然会偶然发现这个问题

当用于POST http请求的控制器方法呈现JSON而不是重定向时,这个问题也会更具体地发生。如果此方法具有before_操作,并且before_操作尝试“重定向到”,而不是按照最初的意图呈现JSON,则会弹出错误

要修复它,只需确保该方法的before_操作也会呈现响应,而不是尝试重定向响应

例如:

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

你能提供你正在使用的控制器代码吗?一张图片值1000字,但是一些代码可以回答你的问题!