您的位置:首页技术文章
文章详情页

django+vue实现注册登录的示例代码

浏览:69日期:2023-11-24 13:02:48
注册

前台利用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注册登录内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Vue
相关文章: