Rails响应取决于http请求格式

时间:2012-03-04 13:17:47

标签: ruby-on-rails json http devise

我想构建一个网站,它可以响应正常的浏览器请求,以及使用Android应用中的JSON的移动请求。 我使用devise进行身份验证。 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中执行了哪种情况。 如果创建一个post请求,则传递登录详细信息,如下所示:

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格式的请求,为什么我会得到该响应?

1 个答案:

答案 0 :(得分:0)

我做了它的工作添加:-H“接受:application / json”