我编写了一个 django webservice,它应该被我的 iOS 应用程序使用。我设法让 GET 请求正常工作,没有特别的问题,但是当我开始使用 POST 的那一刻,我得到 403。我读到它可能是 csrf,所以我尝试了
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
当然它有效!
这是我的 Django 查看代码
questionAnswer = request.POST['questionAnswer']
facebookID = request.POST['facebookID']
if Question.objects.get(pk=int(question_id)).meaning == questionAnswer:
u = User.objects.get(fbid = facebookID)
u.questions_answered = u.questions_answered + 1
u.save()
dictForSend = {'didAnswerCorrect' : 'True'}
jsonq = json.dumps(dictForSend)
return HttpResponse(jsonq, content_type='application/json')
else:
dictForSend = {'didAnswerCorrect' : 'False'}
jsonq = json.dumps(dictForSend)
return HttpResponse(jsonq, content_type='application/json')
这是我的目标c代码
NSDictionary *postDict = @{ @"questionAnswer": questionAnswer, @"facebookID": facebookID};
NSString *myDictInJSON = [postDict JSONRepresentation];
NSData *postData = [myDictInJSON dataUsingEncoding:NSUTF8StringEncoding];
NSString *URLForSend = [NSString stringWithFormat:(@"http://127.0.0.1:8000/questions/checkanswer/%@/") , questionID ];
NSURL *url = [NSURL URLWithString:URLForSend];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"%@", JSON);
} failure:nil];
[operation start];
终端线
"POST /questions/checkanswer/1/ HTTP/1.1" 403 2282
知道如何将 csrf 合并到我的应用程序中吗?