前端(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请求
相关推荐
沛沛老爹6 分钟前
Web开发者实战RAG评估:从指标到工程化验证体系
前端·人工智能·llm·agent·rag·评估
清水白石00810 分钟前
《深入 Python 上下文管理器:contextlib.contextmanager 与类实现方式的底层差异全景解析》
开发语言·python
程序员佳佳12 分钟前
GPT-4时代终结?GPT-5.2与Banana Pro实测数据公开,普通开发者如何接住这泼天富贵
开发语言·python·gpt·chatgpt·重构·api·midjourney
软件技术NINI26 分钟前
JavaScript性能优化实战指南
前端·css·学习·html
问道飞鱼34 分钟前
【Rust编程语言】Rust数据类型全面解析
开发语言·后端·rust·数据类型
Blossom.11842 分钟前
多模态大模型LoRA微调实战:从零构建企业级图文检索系统
人工智能·python·深度学习·学习·react.js·django·transformer
小钻风33661 小时前
软件测试: 从入门到实践 (接口测试)
软件测试·python
前端小配角1 小时前
React难上手原因找到了,原来是因为坑太多了。。。
前端
是你的小橘呀1 小时前
零基础也能懂!React Hooks实战手册:useState/useEffect上手就会,告别类组件
前端·架构
xhxxx1 小时前
从样式到结构:TailwindCss + Fragment 如何让 React 代码更干净、更高效
前端·css·react.js