django vue 前後端分離csrf驗證問題
阿新 • • 發佈:2018-12-19
前言
之前寫過單獨的一篇相關django跨域配置部分配置,故這裡忽略。
vue配置部分
檔案axios.js
let config = {
baseURL: 'http://localhost:8000/',
xsrfCookieName: 'csrftoken',
xsrfHeaderName: 'X-CSRFToken',
withCredentials: true,
//以上三個引數為我新增的csrf相關的必須引數
};
元件呼叫部分示例
let data = new FormData();
data.append('email', this.ruleForm. email);
data.append('password', this.ruleForm.password_1);
this.axios({
method: 'get',
url: 'signup/',
}).then(
res => {console.log(res);
console.log(this.token);
this.axios({
method: 'post',
url: 'signup/',
data: data,
}).then(
res => this.user= this.ruleForm.email
).catch(function (error) {
console.log(error);
}
django配置部分
views示例
from django.shortcuts import render, HttpResponse
from django import views
from .models import *
import json
from django.views.decorators.csrf import get_token
class Signup(BaseView):
def get(self, req):
token = get_token(req)
self.resp['code'] = '0000'
self.resp['msg'] = 'success'
self.resp['token'] = token
return HttpResponse(json.dumps(self.resp), content_type="application/json")
def post(self, req):
email = req.POST.get('email', '')
password = req.POST.get('password_1', '')
print('<email: %s>' % email )
print(req.META.get('CSRF_COOKIE'))
age = 0
req.META["CSRF_COOKIE_USED"] = True
group = Group.objects.get(name='白丁')
User.objects.create(email=email, pwd=password, group=group)
self.resp['code'] = '0000'
self.resp['msg'] = 'success'
return HttpResponse(json.dumps(self.resp), content_type="application/json")
上面的Baseview 基本上就是views.View , 可以忽略
以上內容也是自己經過兩天在網上各種查詢 可以說是都是一堆坑把 以上就是精華 ?