【发布时间】:2019-08-16 14:22:38
【问题描述】:
我使用 Django rest 框架作为我的后端 (api),并使用 React 作为前端。
现在我想将表单数据发布到后端。出于安全考虑,我想使用csrf 保护。所以我尝试使用 Django 发送的csrftoken cookie 为我的axios 请求手动设置csrf 标头。
For this I am using the method as recommended in the Django documentation: Link
我遇到的问题是我需要在我的机器上安装 cookie,然后才能将它添加到标头中,而且我不知道如何让 Django 返回 cookie。
主要问题:如何在我的机器上获取csrftoken cookie? (虽然 React 正在呈现表单,但(最初)不需要与 Django 后端进行任何通信)
另外,如果您发现我的代码有任何问题,我很想知道。
我的代码
这是我当前的代码,我将描述我尝试过的事情:
django views.py:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def contact(request):
if request.method == "POST":
print(request.data)
if request.method == "GET":
return request
最初,我只有上述函数的 POST 部分。但是由于我似乎没有 Django 发送给我的csrftoken cookie,所以我尝试使用 GET 向视图添加功能以获取该 cookie。 (我也试过返回一个HttpResponse(""),没有效果)。
我怎么知道我没有 cookie? 我正在使用 Chrome,转到设置 > 高级 > 内容设置 > cookie > 查看所有 cookie 和站点数据
我在这里签入“127.0.0.1”,因为 React 在“127.0.0.1:3000”运行(而 Django 在“127.0.0.1:8000”运行)。
最初,我确实看到了一个名为“csrftoken”的 cookie,看起来像我需要的那个。即使我的代码不起作用,我也无法将数据发布到后端。然后我删除了 cookie,从那以后我无法取回它。
稍后添加: 我还检查了是否使用 Chrome 开发工具(在应用程序 > cookie 下)看到了 cookie。
我的 axios 请求:
var axios = require('axios')
var jQuery = require('jquery')
module.exports = {
...
submitForm: function(bodyFormData) {
console.log("api.submitForm executes")
axios({
method: 'post',
url: 'http://127.0.0.1:8000/customer/contact/',
data: bodyFormData,
config: { headers: {'Content-Type': 'multipart/form-data' }},
headers: {"X-CSRFToken": this.getCookieValue('csrftoken')}
})
.then(function(response) {
console.log('response success, response + data:')
console.log(response)
console.log(response.data)
return response.data
})
.catch(function(response) {
console.log('response error, response + data:')
console.log(response)
console.log(response.data)
})
},
getCookieValue: function(name) {
this.getCSRFCookie()
let cookieValue = null
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(";")
for (let i = 0; i < cookies.length; i++) {
let cookie = jQuery.trim(cookies[i])
if (cookie.substring(name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1))
break
}
}
}
console.log("cookieValue: " + cookieValue)
return cookieValue
},
getCSRFCookie: function() {
console.log("getCSRFCookie")
axios.get('http://127.0.0.1:8000/customer/contact/')
}
}
查看上面的代码时,我发现即使发送了 cookie,也可能会出现问题。我可以想象获取cookie的请求还没有完成,而正在执行向后端发送表单数据的POST请求。
也许我可以通过在加载表单时执行获取 cookie 的请求来解决这个问题,而不是在发送表单时。但我现在主要关心的是首先访问 cookie。
提前致谢!
【问题讨论】:
-
我遇到了同样的问题。我可以看到你已经等待了七个月的答案,不是很有希望
标签: python django reactjs csrf axios