当前位置:首页 > VUE

vue和django实现登录

2026-01-21 01:09:14VUE

实现Vue与Django登录功能

前端(Vue)部分

安装axios用于发送HTTP请求

npm install axios

创建登录表单组件(Login.vue)

<template>
  <div>
    <input v-model="username" placeholder="用户名">
    <input v-model="password" type="password" placeholder="密码">
    <button @click="login">登录</button>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    login() {
      axios.post('http://localhost:8000/api/login/', {
        username: this.username,
        password: this.password
      })
      .then(response => {
        localStorage.setItem('token', response.data.token);
        this.$router.push('/dashboard');
      })
      .catch(error => {
        console.error('登录失败:', error);
      });
    }
  }
}
</script>

配置axios默认设置(main.js)

import axios from 'axios';
axios.defaults.baseURL = 'http://localhost:8000';
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;

后端(Django)部分

安装必要依赖

pip install djangorestframework django-cors-headers

配置settings.py

INSTALLED_APPS = [
    ...
    'rest_framework',
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

创建用户认证视图(views.py)

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from django.contrib.auth import authenticate

class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = authenticate(username=username, password=password)

        if user:
            token, _ = Token.objects.get_or_create(user=user)
            return Response({'token': token.key})
        return Response({'error': '无效凭证'}, status=400)

配置URL路由(urls.py)

from django.urls import path
from .views import LoginView

urlpatterns = [
    path('api/login/', LoginView.as_view(), name='login'),
]

安全增强措施

添加CSRF保护(Vue端)

axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = 'X-CSRFToken';

Django端CSRF配置

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def get_csrf(request):
    return Response({'detail': 'CSRF cookie set'})

用户状态管理

Vue全局路由守卫(router.js)

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!localStorage.getItem('token')) {
      next('/login');
    } else {
      next();
    }
  } else {
    next();
  }
});

Django用户认证中间件

vue和django实现登录

from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated

class ProtectedView(APIView):
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request):
        return Response({'data': '受保护内容'})

标签: vuedjango
分享给朋友:

相关文章

vue实现Siri

vue实现Siri

Vue 实现 Siri 风格语音交互 实现类似 Siri 的语音交互功能需要结合语音识别、语音合成和前端交互逻辑。Vue 作为前端框架,可以很好地管理这些功能的交互状态。 语音识别集成 使用 Web…

vue搜索实现

vue搜索实现

Vue 搜索功能实现方法 基于计算属性的搜索 在 Vue 中可以通过计算属性实现简单的搜索功能。这种方式适合小型数据集,利用 JavaScript 的 filter 方法进行筛选。 data() {…

vue实现换页

vue实现换页

Vue实现页面切换的方法 在Vue中实现页面切换通常可以通过Vue Router来完成。Vue Router是Vue.js官方的路由管理器,用于构建单页面应用(SPA)。以下是几种常见的实现方式:…

lua 实现vue

lua 实现vue

在 Lua 中实现类似 Vue 的响应式框架需要模拟 Vue 的核心功能,包括数据绑定、模板渲染和依赖追踪。以下是实现的关键思路和代码示例: 响应式数据绑定 使用 Lua 的 __index 和 _…

vue 实现穿透

vue 实现穿透

Vue 样式穿透的实现方法 在 Vue 中,样式穿透通常指在带有 scoped 属性的样式块中,强制影响子组件的样式。以下是几种常见的实现方式: 使用 >>> 或 /deep/ 选…

vue怎样实现mvvm

vue怎样实现mvvm

Vue 实现 MVVM 的原理 Vue 的 MVVM(Model-View-ViewModel)模式通过数据绑定和响应式系统实现视图与数据的自动同步。以下是 Vue 实现 MVVM 的核心机制: 数…