-1
蔭在做打字稿Ajax調用它調用內部的WebService。所有端點白衣「GET」的工作,但絲毫「POST」它說AJAX調用返回CSRF失敗
「403紫禁城」 - 「細節:CSRF失敗:CSRF餅乾未設置」
事情,我試圖修復問題:
- 其次https://docs.djangoproject.com/ko/1.11/ref/csrf/
- Tryed刪除 'django.middleware.csrf.CsrfViewMiddleware'
- Tryed @csrf_exempt
沒有這個工作過,每次仍然出現同樣的錯誤。
這是我在打字稿代碼:
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"))
...
介紹如何試圖使用'@ csrf_exempt'。 [mcve] –
django文檔提供了一個如何使用'jQuery.ajax()'將ajax請求包含CSRF標記的例子。你必須包含一個'X-CSRFToken'頭文件。 https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax –
@HåkenLid我tryed:csrf_exempt(views.ChatMessageAPIEndpoint.as_view()),我試着將它設置爲端點方法前的註釋 – Tim