使用RestKit iOS 5在轨道上发布时出现错误404



我在Restkit+iOS 5+Rails上遇到了一个奇怪的问题:当我试图在服务器上发布这样的帖子时:

NSArray *topicsList=[self.topicsTV.text componentsSeparatedByString:@","]; 
RKParams *params = [NSDictionary dictionaryWithObjectsAndKeys: self.questionTV.text,@"question[text]", 
                                                               self.descriptionTV.text,@"question[detail]",                       
                                                                topicsList,@"topics[]", nil
                    ];
[[RKClient sharedClient] post:@"/questions.json" params:params delegate:self];

日志如下:

2012-01-11 17:24:21.725 APP[29087:fb03] I restkit.network:RKRequest.m:562 Status Code: 401
2012-01-11 17:24:21.725 APP[29087:fb03] I restkit.network:RKRequest.m:563 Body: {"error":"You have to register or login."}

注意,在发布之前,我100%登录,因为我可以访问一些私人内容,而如果我刷新私人内容(发送到服务器),就会出现以下错误:

2012-01-11 17:35:51.337 APP[29087:fb03] D restkit.network.queue:RKRequestQueue.m:455 Request <RKObjectLoader: 0x811c360> failed loading in queue <RKRequestQueue: 0xc60ea10 name=(null) suspended=NO requestCount=0 loadingCount=0/5> with error: The operation couldn’t be completed. (org.restkit.RestKit.ErrorDomain error 1004.).(Now loading 0 of 5).

那次手术让我退出了吗?我应该如何保持登录会话的有效性?

可能发生的情况是rails应用程序在您的应用程序运行POST请求时无法验证CSRF令牌。当您运行GET请求时,它不需要检查令牌(因为GET请求不会更改任何内容)。这就是为什么你可以用用户名和密码获取一些东西,但不能发布一些东西。这篇博文提供了更多信息。

我发现有帮助的是,我禁用了对任何JSON请求的检查。

# In your application_controller.rb
skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| 
  c.request.format == 'application/json' }

当然,你也可以这样做:

# Or this in your application_controller.rb
def verified_request?
  if request.content_type == "application/json"
    true
  else
    super()
  end
end

这两种方法都允许JSON请求忽略令牌,并且您可以适当地CRUD。只要知道你在做什么,如果你选择忽略检查。

此外:https://github.com/rails/rails/issues/3041

最新更新