vue和django实现登录
实现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用户认证中间件
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': '受保护内容'})






