1. 程式人生 > >django 解決ajax 請求csrf跨域問題,解決403 forbidden

django 解決ajax 請求csrf跨域問題,解決403 forbidden

現象: 請求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}
})