我有一个用于 iPad 应用程序的 API。控制器接受 json 并返回 json。当我在本地运行服务器并使用 ISO 模拟器时,POST 请求工作,但是当我在部署到 heroku 后点击 POST 请求时,我作为 JSON 发送的所有参数都为零。
观看 heroku 日志,我在提出请求时得到以下信息。
at=info method=POST path=/note/update host=myapp.herokuapp.com fwd="174.50.210.40" dyno=web.1 connect=0ms service=755ms status=500 bytes=643
2013-04-11T16:51:30.907621+00:00 app[web.1]:
2013-04-11T16:51:30.908272+00:00 app[web.1]: Processing by MyAPIController#update_note as JSON
2013-04-11T16:51:30.908272+00:00 app[web.1]: Parameters: {"myapi"=>{}}
2013-04-11T16:51:30.908272+00:00 app[web.1]: Completed 500 Internal Server Error in 551ms
我在控制器中的操作如下所示。
def update_note
puts "debug note update #{ params[:note] }"
uuid = params[:uuid]
user = User.find_by_uuid(uuid)
noteid = params[:note][:note_id] if params[:note][:note_id]
if !user.nil?
note = nil
note = user.notes.find(noteid) if !noteid.nil?
if !note.nil?
user.notes.find(noteid)
note.update_attributes!(params[:note])
else
note = user.notes.build(params[:note])
note.save
end
render :json => {:result => note}
else
render :json => {:error => "nope"}
end
end
我的路线文件有以下内容
match '/note/update' => 'myapi#update_note'
对于熟悉objective-c的您,这里是发出请求的代码
NSDictionary *noteVo = [NSDictionary dictionaryWithObjectsAndKeys:note->title, @"title", note->body, @"body", note->note_id, @"note_id", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:[_dm getUser]->uuid, @"uuid", noteVo, @"note", true, @"remote", nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&writeError];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:[BASE_URL stringByAppendingString:@"note/update"]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];