2017-08-30 61 views
-1

荫在做打字稿Ajax调用它调用内部的WebService。所有端点白衣“GET”的工作,但丝毫“POST”它说AJAX调用返回CSRF失败

“403紫禁城” - “细节:CSRF失败:CSRF饼干未设置”

事情,我试图修复问题:

没有这个工作过,每次仍然出现同样的错误。

这是我在打字稿代码:

sendMessage(message, receiverId){ 
    let self = this; 
    var message_obj = "{\"id\":\""+ GUID.generateGUID() +"\",\"message\":\""+ message +"\",\"receiverId\":\""+ receiverId + "\",\"moddate\":\""+ Date.now() +"\"}"; 
    var message_json = JSON.parse(message_obj); 
    $.ajax({ 
     type: "POST", 
     url: "/chat/message/", 
     data:{"message_object":message_json}, 
     credentials: 'same-origin', 
     success: function (response) { 
      alert(response); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      alert(errorThrown); 
     } 
    }) 
} 

这是一个工作AJAX调用的例子:

getMessages(){ 
    let self = this; 
    $.ajax({ 
     type: "GET", 
     url: "/chat/message/", 
     dataType: "json", 
     success: function (response) { 
      response = JSON.stringify(response); 
      alert(response); 
     }, 
     error: function(jqXHR, textStatus, errorThrown){ 
      alert(errorThrown); 
     } 
    }) 
} 

编辑:

这里是我tryed使用csrf_exempt:

URLS.PY

from django.conf.urls import url 
from django.views.decorators.csrf import csrf_exempt 

from chat_api import views 

urlpatterns = [ 
    url(r'^message/$', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())), 
    url(r'^message/(?P<commit>([0-9a-fA-F])+)', csrf_exempt(views.ChatMessageAPIEndpoint.as_view())), 
    url(r'^devicekey/(?P<devid>([\w+-:])+)', views.DeviceAPIEndpoint.as_view()), 
    url(r'^devicekey/$', views.DeviceAPIEndpoint.as_view()), 
    url(r'^contacts/$', views.ContactAPIEndpoint.as_view()), 
    url(r'^read/$', views.ReadStatusEndpoint.as_view()), 
] 

VIEWS.PY

@csrf_exempt 
    @need_post_parameters([PARAM_MESSAGE_OBJ]) 
    def post(self, request, *args, **kwargs): 
     data = request.POST.get(PARAM_MESSAGE_OBJ) 

     try: 
      message_obj = json.loads(data) 
     except Exception as e: 
      return HttpResponseBadRequest(error_json("Could not parse JSON")) 
... 
+0

介绍如何试图使用'@ csrf_exempt'。 [mcve] –

+0

django文档提供了一个如何使用'jQuery.ajax()'将a​​jax请求包含CSRF标记的例子。你必须包含一个'X-CSRFToken'头文件。 https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax –

+0

@HåkenLid我tryed:csrf_exempt(views.ChatMessageAPIEndpoint.as_view()),我试着将它设置为端点方法前的注释 – Tim

回答

0

我已经找到了错误,我将它张贴在这里平等的错误:其中使用

我的课表中Views.py“ Oauth2APIView“! 它更改成“查看”没有解决这个问题对我来说!