weixin_33725126 2017-08-30 08:02 采纳率: 0%
浏览 27

AJAX呼叫传回CSRF失败

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:

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"))
...
  • 写回答

1条回答 默认 最新

  • weixin_33743703 2017-08-30 09:28
    关注

    I have found the mistake and i will post it here for equal errors:

    My Classes in Views.py where using "Oauth2APIView"! Changing it into "View" did solve the problem for me!

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100