django 解决ajax 请求csrf跨域问题,解决403 forbidden

版权声明:本文为博主原创文章,未经博主允许不得转载。转载请注明出处,并告知本人 https://blog.csdn.net/the_conquer_zzy/article/details/83796261

现象: 请求403 ,提示跨域

原因:

项目setting.py 中installed app 里面有

'django.middleware.csrf.CsrfViewMiddleware',

###解决过程:查看请求发现 cookie 有csrftoken
所以利用js 获取csrftoken

核心语句   document.cookie()会返回所有的cookie 
cookie 的结构如下: name1=value1;name2=value2
所以遍历每一项cookie 找到csrftoken的value

具体代码:

function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                     }
                    }
                 }
             return cookieValue;
            }

最后在ajax post 中传入一个key为csrfmiddlewaretoken

$.ajax({
	type:"POST",
	data:{"csrfmiddlewaretoken": csrftoken_value, key2:value2}
})

猜你喜欢

转载自blog.csdn.net/the_conquer_zzy/article/details/83796261
今日推荐