vue加django实现登录
Vue 与 Django 实现登录功能
技术栈分工
- Django:提供 RESTful API 接口,处理用户认证(如 JWT 或 Session),数据库操作。
- Vue:构建前端界面,发送登录请求,管理用户状态(如 Vuex 或 Pinia)。
Django 后端实现
安装必要依赖
pip install django djangorestframework django-cors-headers
配置 Django 项目
- 创建用户认证模型(Django 默认已提供
User模型)。 - 在
settings.py中启用相关配置:INSTALLED_APPS = [ ..., 'rest_framework', 'corsheaders', ]
MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', ]
CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", # Vue 开发服务器地址 ]
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', ], }
创建登录 API
在 `views.py` 中编写登录逻辑:
```python
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth import authenticate, login
class LoginView(APIView):
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return Response({'status': 'success'})
return Response({'status': 'error'}, status=400)
配置路由
在 urls.py 中添加路由:
from django.urls import path
from .views import LoginView
urlpatterns = [
path('api/login/', LoginView.as_view(), name='login'),
]
Vue 前端实现
安装必要依赖
npm install axios vuex
创建登录组件
在 Login.vue 中实现表单和请求:
<template>
<form @submit.prevent="handleLogin">
<input v-model="username" placeholder="Username" />
<input v-model="password" type="password" placeholder="Password" />
<button type="submit">Login</button>
</form>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
username: '',
password: '',
};
},
methods: {
async handleLogin() {
try {
const response = await axios.post('http://localhost:8000/api/login/', {
username: this.username,
password: this.password,
});
if (response.data.status === 'success') {
this.$router.push('/dashboard');
}
} catch (error) {
console.error('Login failed:', error);
}
},
},
};
</script>
状态管理(可选) 使用 Vuex 存储用户登录状态:
// store.js
import { createStore } from 'vuex';
export default createStore({
state: {
isAuthenticated: false,
},
mutations: {
setAuth(state, status) {
state.isAuthenticated = status;
},
},
});
跨域问题解决
开发环境
- Django 的
corsheaders已配置允许 Vue 的源(见CORS_ALLOWED_ORIGINS)。 - 确保 Vue 的
axios请求地址与 Django 服务端口一致。
生产环境
- 部署时配置 Nginx/Apache 反向代理,将 API 请求转发到 Django。
- 示例 Nginx 配置:
location /api { proxy_pass http://django-server:8000; }
安全增强建议
- HTTPS:生产环境启用 HTTPS 加密通信。
- CSRF 保护:Django 默认启用 CSRF,Vue 需在请求中携带 CSRF Token:
axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; - JWT 替代 Session:如需无状态认证,可使用
djangorestframework-simplejwt库。







