- 后端在数据根本性请求post之前,先get一下,不一定是需要要返回内容,只要get一下,
- 前端获取cookie
import Cookies from 'universal-cookie';
let cookies = new Cookies()
// 在执行访问post数据前,使用cookie.get("csrftoken")
// 如果是空的,先请求一下,cookie.get("csrftoken")的值了
// 再然后就post 数据的header添加 'X-CSRFToken': xcsrf,即可
全部前台:
import Cookies from 'universal-cookie';
let cookies = new Cookies()
const get_csrf = async(url = "goods/csrf") => {
await fetch(url).then(res=>res).catch(error=>console.log(error))
}
export const postData = async(url, data)=>{
// Default options are marked with *
// await get_csrf()
// console.log("csrf-",csrf)
let xcsrf = cookies.get('csrftoken')
if(xcsrf === null||xcsrf ===""||xcsrf === undefined){
console.log("获取csrf")
await get_csrf()
xcsrf = cookies.get('csrftoken')
console.log("得到csrf", xcsrf)
}else{
console.log("有xcsrf:",xcsrf)
}
return fetch(url, {
body: JSON.stringify(data), // must match 'Content-Type' header
headers: {
'X-CSRFToken': xcsrf,
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
})
.then(response => response.json()) // parses response to JSON
.catch(error=>console.log(error))
}
"""
url:
path('get', views.get_goods, name='get_goods'),
path('csrf', views.get_csrf, name='get_csrf')
"""
from django.middleware import csrf
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie
def get_csrf(req):
token = csrf.get_token(req)
print("csrf token:", token)
return JsonResponse({'X-CSRFToken': token}, safe=False)
# return HttpResponse()
@ensure_csrf_cookie
def get_goods(req):
return JsonResponse({a:2,b:3}, safe=False)
网友评论