后端 - DRF
中间件 - 跨域请求
from django.utils.deprecation import MiddlewareMixin
class MyCorsMiddle(MiddlewareMixin):
def process_response(self, request, response):
# 允许所有人向我发请求
response['Access-Control-Allow-Origin'] = '*'
if request.method == 'OPTIONS':
# 所有的头信息都允许
response['Access-Control-Allow-Headers'] = '*'
return response
setting - 注册自定义中间件
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"logindemo.MyCorsMiddle.MyCorsMiddle",
]
模型
from django.db import models
# Create your models here.
class Login(models.Model):
"""登录模型类"""
username = models.CharField(max_length=64,unique=True)
passwoed = models.IntegerField()
class Meta:
db_table = "tb_login"
子应用下的serializer
from rest_framework import serializers
from app01 import models
class LoginSerializer(serializers.ModelSerializer):
class Meta:
fields = "__all__"
model = models.Login
视图
from django.shortcuts import render
from .serializer import LoginSerializer
from .models import Login
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
# Create your views here.
class LoginModelView(ModelViewSet):
queryset = Login.objects.all()
serializer_class = LoginSerializer
@action(methods=["post"],detail=False,url_path="login")
def login(self,request):
"""登录视图"""
username = request.data['username']
passwoed = request.data['passwoed']
try:
use_obj = Login.objects.get(username=username)
except Exception as e:
print(123)
return Response({"meg":"该用户不存在"})
if use_obj.passwoed != int(passwoed):
return Response({"meg":"密码错误"})
return Response({"meg":"登录成功!"})
前端 - VUE
src/utils/http.js -- axios前提
import axios from "axios";
//实例化
const http = axios.create({
baseURL:"http://127.0.0.1:8000",
})
export default http
src/utils/router.js -- 路由前提
import {createRouter,createWebHistory,createWebHashHistory} from "vue-router";
const router = createRouter({
history:createWebHistory(),
routes:[
{
path:"/",
name:"Login",
component:import('../views/Login.vue')
},
{
path:"/reg",
name:"reg",
component:import("../views/reg.vue")
},
{
path:"/index",
name:"index",
component:import("../views/index.vue")
},
{
path:"/log",
name:"log",
component:import("../views/log.vue")
}
]
})
export default router
src/views/Login.vue - 导航页面
<template>
<div>
<router-link to="/reg">注册页面</router-link>
<br>
<router-link to="/log">登录页面</router-link>
</div>
</template>
<script setup>
</script>
<style scoped>
</style>
src/views/reg.vue - 注册页面
<template>
<div>
<h1>注册页面</h1>
用户名:<input type="text" v-model="username" @focus="clear">
密码:<input type="password" v-model="pwd">
<button @click="submit">注册</button>
<span class="tips">{{text}}</span>
</div>
</template>
<script setup>
import {ref} from 'vue'
import http from "../utils/http";
import {useRouter} from "vue-router"
let username = ref("")
let pwd = ref("")
let text = ref("")
const router = useRouter()
const clear = ()=>{
text.value = ""
}
// 注册添加用户
const submit = ()=>{
http.post("/user/",{
"username":username.value,
"passwoed":pwd.value
}).then(response=>{
alert("注册成功~~")
router.push('/log')
}).catch(error=>{
text.value = "该用户名已经注册,请重新输入另一个用户名字"
})
}
</script>
<style scoped>
.tips{
color: red;
}
</style>
src/views/log.vue - 登录页面
<template>
<div>
<h1>登录页面</h1>
用户名:<input type="text" v-model="username" @focus="clear_tips">
密码:<input type="password" v-model="pwd">
<button @click="login">登录</button>
<span class="tips">{{login_tips}}</span>
</div>
</template>
<script setup>
import {ref} from 'vue'
import http from "../utils/http";
import {useRouter} from "vue-router"
let username = ref("")
let pwd = ref("")
let login_tips = ref("")
const router = useRouter()
// 消除提示信息
const clear_tips = ()=>{
login_tips.value = ""
}
// 登录校验
const login = ()=>{
http.post("/user/login/",{
"username":username.value,
"passwoed":pwd.value
}).then(response=>{
if(response.data.meg==="登录成功!"){
alert(response.data.meg)
router.push(`/index?username=${username.value}`)
}
else{
login_tips.value = response.data.meg
}
})
}
</script>
<style scoped>
.tips{
color: red;}
</style>
src/views/log.vue - 登录页面
<template>
<h1>欢迎你,{{username}}</h1>
</template>
<script setup>
import {ref} from "vue"
import {useRoute} from 'vue-router'
const route = useRoute()
let username = ref(route.query.username)
</script>
<style scoped>
</style>
效果展示:
导航
注册
登录
主页面
当注册用户已存在,会提示
当登录密码错误或账号不存在,会提示
当注册页面注册成功后,会自动跳转到登录页面。
第一次实现前后端分离的小案例,有什么不足,请各位斧正,谢谢!