【VUE+DRF】案例升级
1、功能完善(简易版)
1.1 后端API校验
基于drf的认证组件实现只有登录之后才能查看
utils/auth.py
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import APIException, AuthenticationFailed
from rest_framework import status
from api import modelsclass MineAuthenticationFailed(APIException):status_code = status.HTTP_200_OKclass MineAuthentcation(BaseAuthentication):def authenticate(self, request):token = request.query_params.get("token")if not token:raise MineAuthenticationFailed("token不存在")user_object = models.UserInfo.objects.filter(token=token).first()if not user_object:raise MineAuthenticationFailed("认证失败")return user_object, token
settings.py
REST_FRAMEWORK = {"DEFAULT_AUTHENTICATION_CLASSES": ["utils.auth.MineAuthentcation"],
}
account.py
class AuthView(MineApiView):authentication_classes = []
1.2 前端校验
axios.js
const _axios = axios.create(config)
const info = userInfoStore()_axios.interceptors.request.use(function (config) {// console.log("请求拦截器:", config)// 1. 去pinia中读取当前用户token// 2. 发送请求时携带tokenif (info.userToken) {if (config.params) {config.params["token"] = info.userToken} else {config.params = {"token": info.userToken}}}return config
})
_axios.interceptors.response.use(function (response) {console.log("响应拦截器:", response)// 认证失败if (response.data.code === "1000") {router.replace({name: "login"})}return response
}, function (error) {console.log("拦截器异常", error)if (error.response.data.code === "1000") {router.replace({name: "login"})}return Promise.reject(error)
})export default _axios
LoginView.vue
const doLogin = function () {// 1、获取数据console.log(msg.value)// 2、发送网络请求_axios.post("/api/auth/", msg.value).then((res) => {console.log(res.data)if (res.data.code === 0){store.doLogin(res.data.data)router.push({name: "home"})} else {error.value = res.data.msgsetTimeout(function (){error.value=""}, 5000)}})
}