[英]how to fix (CSRF token missing or incorrect ) react/redux + django
[英]React Django CSRF token missing or incorrect
在动作文件中的代码:
...
const config = {
headers:{
'Content-type': 'application/json'
}
}
const {data} = await axios.post('http://localhost:8000/api/register/',
{'email':email, 'password':password}, config)
...
它正在工作; 然后localhost:8000移动到package.json作为代理,之后出现CSRF token missing or wrong 的问题,如何解决,谢谢。 应用程序重新启动,没有任何更改。 此外,请求已更改为localhost:3000而不是 8000。
Django 可以通过装饰器在您的 cookies 中提供 CSRF 令牌。 然后你可以从你的 cookies 中得到它,并将其添加为 HTTP header:
from django.views.decorators.csrf import ensure_csrf_cookie
# add this decorator to your main view
# (the one which serves your first html/javascript code, not the /api/register one)
@ensure_csrf_cookie
def index(request):
...
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var 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 config = {
headers:{
'Content-type': 'application/json',
'X-CSRFToken': getCookie("csrftoken") // added the csrf cookie header
}
}
const {data} = await axios.post('http://localhost:8000/api/register/',
{'email':email, 'password':password}, config)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.