前端(vue3)和后端(django)的交互

vue3中:

TypeScript 复制代码
<template>
  <div>
    <h2>注册页面</h2>
    <form @submit.prevent="submitForm">
      <label for="username">用户名:</label>
      <input type="text" id="username" v-model="username" required>
      
      <label for="email">邮箱:</label>
      <input type="email" id="email" v-model="email" required>
      
      <label for="password">密码:</label>
      <input type="password" id="password" v-model="password" required>
      
      <button type="submit">注册</button>
    </form>
  </div>


</template>

<script setup lang="ts">


import { ref } from 'vue';
import axios from 'axios';

    const username = ref('');
    const email = ref('');
    const password = ref('');

    const submitForm = async () => {//构造一个异步函数
      try {
        const userData = {
          username: username.value,
          email: email.value,
          password: password.value
        };
        const response = await axios.post('/home/register/', userData);//await关键词表示会在得到数据之后才继续执行(等一等)
        console.log('注册成功!服务器返回的数据:', response.data);
        // 这里可以根据后端返回的数据进行进一步处理,例如显示成功提示或者跳转页面
      } catch (error) {//error本身也是一个对象
        console.error('注册失败:', error);
        // 这里可以处理错误情况,例如显示错误信息给用户
      }
};

</script>

Django(view):

TypeScript 复制代码
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json

@csrf_exempt#装饰器,防止 CSRF 攻击
def register_user(request):#定义一个注册的视图函数
    if request.method == 'POST':
        try:
            # 从请求体中获取前端发送的数据
            data = json.loads(request.body)#将request请求体中的json数据转化为字典类型的数据结构
            username = data.get('username')#通过get方式获取到前端发送过来是详细信息
            email = data.get('email')
            password = data.get('password')
            
            # 在这里处理注册逻辑,例如创建用户等
            #这里的逻辑是与models交互(省略)

            
            response_data = {'message': '注册成功!', 'username': username}# 成功注册后返回一个成功消息
            return JsonResponse(response_data, status=201)
        
        except Exception as e:#Exception 是 Python 中所有异常类的基类,这个可以捕获到任意错误,同时将捕获到的异常对象赋 e
            return JsonResponse({'error': str(e)}, status=400)#404表示客户端发送了错误的请求
            #同时返回json格式的数据,表示是一个字典,主键是error,值是通过把e变成str类型的数据类型
    return JsonResponse({'error': '只接受POST请求'}, status=405)#405表示使用错误的方法https请求
相关推荐
码事漫谈11 分钟前
Visual Studio 2026真的值得升级吗中国开发者实测报告
后端
液态不合群14 分钟前
DDD驱动低代码开发:从业务流程到领域模型的全链路设计
前端·低代码·架构·ddd
jonyleek18 分钟前
JVS低代码开发中,如何创建自定义前端页面并接入到现有系统中,从创建到接入的全攻略
前端·低代码·前端框架·软件开发
谢尔登43 分钟前
【React】React组件的渲染过程分为哪几个阶段?
前端·javascript·react.js
麦麦大数据1 小时前
F047 vue3+flask微博舆情推荐可视化问答系统
python·flask·知识图谱·neo4j·推荐算法·舆情分析·舆情监测
MediaTea1 小时前
Python 第三方库:Flask(轻量级 Web 框架)
开发语言·前端·后端·python·flask
5***o5001 小时前
前端构建工具缓存清理,解决依赖问题
前端·缓存
q***72561 小时前
Spring Boot + Vue 全栈开发实战指南
vue.js·spring boot·后端
java干货1 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring