Rails响应取决于http请求格式



我想建立一个网站,使用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

这实际上是一个伪代码,只是为了知道哪种情况会在respons_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表示。换句话说,在responsd_to中,它总是执行format.html条目。这个代码出了什么问题?如果我在头中指定这是一个JSON格式的请求,为什么我会得到响应?

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

最新更新