【问题标题】:Rails response depending on http request formatRails 响应取决于 http 请求格式
【发布时间】:2012-03-04 13:17:46
【问题描述】:

我想建立一个网站,既可以响应普通浏览器请求,也可以使用来自 Android 应用程序的 JSON 响应移动请求。 我使用设计进行身份验证。 Web 用户将正常登录,但对于移动使用,我希望他们只发送一次登录名/密码,然后使用身份验证令牌。 为此,我重写了设计会话控制器:

class SessionsController < Devise::SessionsController

skip_before_filter :verify_authenticity_token
respond_to :html, :json

def create
  resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new")
  set_flash_message(:notice, :signed_in) if is_navigational_format?
  sign_in(resource_name, resource)

  obj1 = MyModel.find(21)
  obj2 = MyModel.find(22)

  respond_to do |format|
      format.html do
      render :json => obj1
      end
      format.json do
      render :json => obj2
      end
  end
end
def destroy
    super
end 
end

这实际上是一个虚拟代码,只是为了知道在respond_to中执行了哪个案例。 如果创建一个发布请求,传递登录详细信息,如下所示:

curl -v -X POST -d '{"user" : { "email" : "myemail@gmail.com", "password" : "123456"}}' -H "Content-Type:application/json" http://localhost:3000/users/sign_in

响应是 obj1 的 JSON 表示。换句话说,在respond_to 中它总是执行format.html 条目。 这段代码有什么问题?如果我在标头中指定这是 JSON 格式的请求,为什么会收到该响应?

【问题讨论】:

  • 我让它工作,添加: -H "Accept:application/json" 一天试图解决这个问题,我在发布到 stackoverflow 10 分钟后解决了这个问题。抱歉,我希望至少它可以帮助某人。
  • 请发表您的评论作为答案并接受它。

标签: ruby-on-rails json http devise


【解决方案1】:

我添加了:-H "Accept:application/json"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2015-03-24
    相关资源
    最近更新 更多