I send a POST request from IPhone to Django and get "CSRF verification failed", which I can't perfectly understand. I tried to find a good solution over the internet, but I couldn't . is there any simple way to POST to django?
this is my code:
NSString *post =[NSString stringWithFormat:@"s=aaa&r=k&c=gg"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:(@"http://localhost:8000/messages/views/")]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(data);
Normally this boils down to setting the headers correctly. There is an answer that already details this. The relevant part you need is this:
xhr.setRequestHeader("X-CSRFToken", token)
See the linked answer for details on getting the token from the cookies, for brevity I didn't copy it from there. I don't really know the context of your code, so this method of retrieval might not directly apply. Regardless, you need to get the token somehow.
When you have the token, add a header to the NSMutableURLRequest
. Upon posting the request, the error should be gone.
[request addValue:token forHTTPHeaderField:@"X-CSRFToken"];
Am I wrong or it just don't make sense to use this on native app?
In that case, you could just disable this protection using this decorator:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def view_without_csrf_protection(request):
pass
来源:https://stackoverflow.com/questions/8487542/iphone-posting-to-django-and-gets-csrf-verification-failed