【发布时间】: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 只包含一个没有任何表单标签的按钮
【问题讨论】: