我正在使用 vanilla js 向 django 发出 ajax post 请求

时间:2021-03-07 00:55:58

标签: javascript django ajax

我正在尝试向 django 发出 ajax post 请求,这是 js 片段

const xhr = new XMLHttpRequest();

            console.log(xhr.readyState);
            
            xhr.open('POST', '');

            var data = '{% csrf_token %}';

            console.log(data);

            console.log(typeof(data));

            xhr.setRequestHeader('X-CSRF-Token', data);
            
            xhr.onload = function(){

                console.log(xhr.readyState);

                console.log(xhr.status);

                if(xhr.status == 200){
                
                    console.log(JSON.parse(xhr.responseText));
                
                }else{
                    console.log("Something went wrong!!");
                }

            }
            
            xhr.send({'userId' : userId})
        }

这是我的错误日志: enter image description here

我收到了 403 禁止错误,有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

此功能应该为您提供csrf-token

function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim();
        // 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;
}

然后:

const csrftoken = getCookie('csrftoken');

获取csrf-token

同样值得关注的是改变X-CSRF-Token

xhr.setRequestHeader('X-CSRF-Token', data);

X-CSRFToken

xhr.setRequestHeader('X-CSRFToken', data);

希望能帮到你

相关问题