当使用 ajax发送post请求是,报错CSRF token missing

当页面需要 是用 ajax想后端提交数据时,需要将 csrfmiddlewaretoken 的值传过去

function up_ajax(){
    data = {
        "name": 'xxxx',
        "phone": 'xxxxxxxxx',
        "csrfmiddlewaretoken":'{{csrf_token}}'  # 这一段,将 csrf token连同表单一起传到后端
    };
    fetch('',{
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json;charset=utf-8',
            "X-CSRFToken": "{{csrf_token}}"  # 在headers中添加 csrf token
        }
    }).then(response => response.text())
    .then(text => {
        document.write(text)
    })
}

 

posted @ 2022-07-09 15:59  JiZhaoG  阅读(299)  评论(0)    收藏  举报