CSRF Failed: CSRF token missing or incorrect

前端 未结 12 942
臣服心动
臣服心动 2020-11-29 02:42

I\'m using Django 1.7 and django-rest-framework.

I made an API that returns me some JSON data putting this in my settings.py

REST_FRAMEW         


        
12条回答
  •  再見小時候
    2020-11-29 03:26

    This is what i did to solve it, i included csrf token to the form and using jquery/ javascrip got the csrf token like this when document loaded

    var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value');
    

    the included it on jquery headers as follow

     $.ajax({
                type: "POST",
                url: "/api/endpoint/",
                data: newEndpoint,
                headers:{"X-CSRFToken": $crf_token},
                success: function (newEnd) {
                    console.log(newEnd);
                    add_end(newEnd);
                },
                error: function () {
                    alert("There was an error")
                }
            });
    

提交回复
热议问题