django+vue實現注冊登錄的示例代碼
前臺利用vue中的axios進行傳值,將獲取到的賬號密碼以form表單的形式發送給后臺。form表單的作用就是采集數據,也就是在前臺頁面中獲取用戶輸入的值。numberValidateForm:前臺定義的表單$axios使用時需要在main.js中全局注冊,.then代表成功后進行的操作,.catch代表失敗后進行的操作
submitForm(formName) { let data = new FormData() data.append(’username’,this.numberValidateForm.name) data.append(’password’,this.numberValidateForm.pass) this.$axios.post(’/api/register/’,data).then((res) => {this.$router.push({ name: 'login' }) // 路由跳轉 }).catch((res) => { console.log('error submit!!'); return false; }) }
使用$axios進行跨域驗證,首先得設置代理,然后在請求頭中加入X-CSRFToken
vue.config.js
代理
proxy: {'/api':{ target:'http://127.0.0.1:8000/', changeOrigin: true // 是否代理} },//設置代理,
main.js
import Axios from ’axios’Vue.prototype.$axios = Axioslet getCookie = function (cookie) { let reg = /csrftoken=([w]+)[;]?/g return reg.exec(cookie)[1]}Axios.interceptors.request.use( function(config) { // 在post請求前統一添加X-CSRFToken的header信息 let cookie = document.cookie; if(cookie && config.method == ’post’){ config.headers[’X-CSRFToken’] = getCookie(cookie); } return config; }, function(error) { // Do something with request error return Promise.reject(error); });登錄
submitForm(formName) { this.$refs[formName].validate(valid => { //vue前臺的驗證規則if (valid) { let data = new FormData() data.append(’username’,this.numberValidateForm.name) data.append(’password’,this.numberValidateForm.pass) this.$axios.post(’/api/login/’,data).then((res) => { if(res.data.code == 'ok'){ console.log(12345678) this.$router.push({name:'firstpage'}) } })} else { console.log('error submit!!'); return false;} }); },
view.py
django后臺視圖函數
from django.shortcuts import renderfrom django.views import Viewfrom django.http import HttpResponse,JsonResponsefrom django.contrib.auth.models import User # django封裝好的驗證功能from django.contrib import authclass Login(View): def post(self,request):try: user = request.POST.get(’username’,None) pwd = request.POST.get(’password’,None) # 驗證密碼 obj = auth.authenticate(request,username=user,password=pwd) if obj:return JsonResponse({’code’:’ok’,’message’:’賬號密碼驗證成功’})except: return JsonResponse({’code’:’no’,’message’:’驗證失敗’})class Register(View): def post(self, request):try: username = request.POST.get(’username’,None) password = request.POST.get(’password’,None) user = User.objects.create_user(username=username,password=password) user.save()except: return JsonResponse({’code’:’no’,’message’:’注冊失敗’})return JsonResponse({’code’:’ok’,’message’:’注冊成功’})
到此這篇關于django+vue實現注冊登錄的示例代碼的文章就介紹到這了,更多相關django+vue注冊登錄內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: