Forbidden (CSRF token missing or incorrect.):

半世苍凉 提交于 2020-08-22 11:52:57

问题


I am making ajax call like below:

var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken': '{{ csrf_token }}'};
    $.ajax({
        type: 'POST',
        url:"/issuebook",
        data:data_dict,
        processData: false,
        contentType: false,
        success:function(response)
        {
        }
    });

urls.py is:

urlpatterns = [
url(r'^$',views.checkLogin,name='checklogin'),
url(r'^mylibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.MyLibrary.as_view()),name='mylibrary'),
url(r'^centrallibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.CentralLibrary.as_view()),name='centrallibrary'),
url(r'^issuebook$',login_required(views.IssueBookView.as_view()),name='issuebook'), 

]

I am getting "Forbidden (CSRF token missing or incorrect.): /issuebook" error on ajax call.

The csrf token in ajax call is getting rendered as:

var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
                    $.ajax({
                        type: 'POST',
                        url:"/issuebook",
                        data:data_dict,
                        contentType: false,
                        success:function(response)
                        {
                        }
                    });

回答1:


This error is caused by processData and contentType options in your ajax function. Removing these two options will fix the issue.

Explanation: The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded. Whereas, if you set processData: false it won't encode the POST parmaters and contentType: false will send ajax POST request as text/plain.



来源:https://stackoverflow.com/questions/36291186/forbidden-csrf-token-missing-or-incorrect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!