前端(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请求
相关推荐
golang学习记几秒前
Python 3.14 正式发布:七大重磅新特性详解
后端
C2X10 分钟前
Vue3.0 学习总结
前端
用户40993225021211 分钟前
PostgreSQL里的子查询和CTE居然在性能上“掐架”?到底该站哪边?
后端·ai编程·trae
xxxcq12 分钟前
Go微服务网关开发(2):路由转发功能的实现
后端
汤姆Tom12 分钟前
CSS 新特性与未来趋势
前端·css·面试
尘世中一位迷途小书童12 分钟前
🚀 pnpm + Monorepo 实战指南:现代前端项目管理的最佳实践
前端·架构
努力努力再努力wz13 分钟前
【C++进阶系列】:万字详解智能指针(附模拟实现的源码)
java·linux·c语言·开发语言·数据结构·c++·python
杨超越luckly26 分钟前
HTML应用指南:利用GET请求获取全国中国建设银行网点位置信息
前端·arcgis·html·数据可视化·门店数据
王翼鹏28 分钟前
html 全角空格和半角空格
前端·html
敲代码的嘎仔28 分钟前
JavaWeb零基础学习Day2——JS & Vue
java·开发语言·前端·javascript·数据结构·学习·算法