【问题标题】:django retrieve csrf tokendjango 检索 csrf 令牌
【发布时间】:2019-05-06 15:44:40
【问题描述】:

在我的 Web 应用程序中,我需要检索 csrf 令牌以通​​过 xmlhttprequest 发送一些数据,但我在服务器上收到错误消息,如“django\middleware\clickjacking.py”,第 26 行,在 process_response 如果 response.get('X-Frame-Options') 不是无: AttributeError: 'str' object has no attribute 'get' "。这是我的代码

//views.py

from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template.context_processors import csrf

def interfacePage(request):
    return render(request, "interfacePage.html", {})

def interfacePageSubmit(request):
    if request.method == 'POST':
        datarecvd = request.POST['data']
        return render(request, "interfacePageSubmit.html", {})
    else:
        print("in def interfacePageSubmit")
        csrf1 = str(csrf(request)['csrf_token'])
        return csrf1

//interfacePage.html

function sumbit() {

        var xhr = new XMLHttpRequest();
        var url = {% url 'interfacePageSubmit' %};


        xhr.open("GET", url, false);
        xhr.withCredentials = false;
        xhr.setRequestHeader("x-csrf-token", "fetch");    
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        var data = null;
        xhr.send(data);
        console.log(xhr.readyState);
        console.log(xhr.status);

        if (xhr.readyState === 4 && xhr.status === 200) {
            var csrfToken = xhr.getResponseHeader('x-csrf-token');
            url = {% url 'interfacePageSubmit' %};
            xhr.open("POST", url, true);
            xhr.withCredentials = false;
            xhr.setRequestHeader("Accept", "application/json");
            xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
            xhr.setRequestHeader('x-csrf-token', csrfToken); 
        }

**/ further code goes here

请注意我的“interfacePage.html 只包含一个没有任何表单标签的按钮

【问题讨论】:

    标签: python django


    【解决方案1】:

    您需要返回一个HttpResponse。试试这样的:

    def interfacePageSubmit(request):
        # . . . 
        csrf1 = str(csrf(request)['csrf_token'])
        json_data = json.dumps(csrf1)
        return HttpResponse(json_data, content_type='json')
    

    【讨论】:

    • 我被禁止(CSRF 令牌丢失或不正确。):/interfacePageSubmit/ 当我使用 POST 方法通过将获取的 csrf 令牌添加到标头来发送 xmlHttpRequest 时出错
    猜你喜欢
    • 2020-10-29
    • 2015-06-09
    • 2013-08-11
    • 2016-08-03
    • 2021-07-14
    • 2015-10-25
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多