Django的csrf
如果前端请求,后端返回信息如下,说明前端请求缺乏X-CSRFToken
头,或者这个header头的值不正确
CSRF Failed: CSRF token missing or incorrect
解决办法:
1、添加X-CSRFToken
function getCookie (name) { let value = '; ' + document.cookie; let parts = value.split('; ' + name + '='); if (parts.length === 2) return parts.pop().split(';').shift() } export function PostJson(url, datas) { return fetch(url, { method: 'post', credentials: 'include', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, body: JSON.stringify(datas) }) .then(res => { const data = res.json(); if (data.redirect) { window.location.replace(data.redirect); } return data; }); }
2、添加屏蔽装饰器
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def some_view(request): #...
3、注释掉django工程settings.py中的中间件
#'django.middleware.csrf.CsrfViewMiddleware'
参考:
1、http://www.cnblogs.com/zhujiabin/p/8260288.html
2、https://blog.csdn.net/lohiaufung/article/details/80792334