1. 程式人生 > 程式設計 >django+vue實現註冊登入的示例程式碼

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  // 是否代理
        }
    },www.cppcns.com//設定代理,

main.js

import Axios from 'axios'
Vue.prototype.$axios = Axios
let 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 render
from django.views import View
from dwww.cppcns.comjango.http import HttpResponse,JsonResponse
from django.contrib.auth.models import User  # django封裝好的驗證功能
from django.contrib import auth
class Login(View):
    def post(self,request):
        try:
            user = request.POST.ge程式設計客棧t('username',None)
            pwd = request.POST.get('password',None)
            # 驗證密碼
            obj = auth.authenticate(reques程式設計客棧t,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註冊登入內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!