Iam doing an ajax call in Typescript which calls an internal Webservice. All endpoints whit "GET" are working, but whit "POST" it says
"403 Forbidden" - "detail: CSRF Failed: CSRF cookie not set"
Things i tried to fix the issue:
- Followed https://docs.djangoproject.com/ko/1.11/ref/csrf/
- Tryed to delete 'django.middleware.csrf.CsrfViewMiddleware'
- Tryed @csrf_exempt
Nothing of this has worked, everytime still the same error occurs.
Here is my code in Typescript:
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);
}
})
}
This is an example of an working ajax call:
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);
}
})
}
EDIT:
Here is where i tryed to use 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"))
...