当前位置:首页 > 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)部分

安装必要依赖

vue和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)

vue和django实现登录

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用户认证中间件

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实现sql操作

vue实现sql操作

在Vue中实现SQL操作通常需要结合后端服务或本地数据库技术,因为前端JavaScript无法直接连接SQL数据库。以下是几种常见的实现方式: 通过API与后端交互 Vue前端通过HTTP请求(如…

用vue实现滑动输入条

用vue实现滑动输入条

使用 Vue 实现滑动输入条 使用原生 HTML5 input range 实现 在 Vue 模板中直接使用 <input type="range">,通过 v-model 绑定数据:…

vue实现一个tab栏

vue实现一个tab栏

Vue 实现 Tab 栏 基础实现(选项式 API) <template> <div class="tab-container"> <div class="t…

vue   实现单选

vue 实现单选

Vue 实现单选功能 在 Vue 中实现单选功能可以通过多种方式,以下是几种常见的方法: 使用原生 <input type="radio"> 绑定 v-model 通过 v-model…

vue实现granfana

vue实现granfana

Vue 实现类似 Grafana 的仪表盘 要在 Vue 中实现类似 Grafana 的仪表盘功能,需要结合数据可视化库、状态管理和 UI 组件。以下是关键步骤和推荐工具: 数据可视化库 使用 E…

vue实现socket

vue实现socket

Vue 中实现 WebSocket 通信 在 Vue 项目中实现 WebSocket 通信可以通过原生 WebSocket API 或第三方库(如 socket.io-client)完成。以下是两种常…