前端(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请求
相关推荐
知识分享小能手1 小时前
React学习教程,从入门到精通, React 属性(Props)语法知识点与案例详解(14)
前端·javascript·vue.js·学习·react.js·vue·react
luckys.one1 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
魔云连洲1 小时前
深入解析:Vue与React的异步批处理更新机制
前端·vue.js·react.js
mCell2 小时前
JavaScript 的多线程能力:Worker
前端·javascript·浏览器
大翻哥哥3 小时前
Python 2025:量化金融与智能交易的新纪元
开发语言·python·金融
言之。3 小时前
Django中的软删除
数据库·django·sqlite
超级无敌攻城狮3 小时前
3 分钟学会!波浪文字动画超详细教程,从 0 到 1 实现「思考中 / 加载中」高级效果
前端
zhousenshan4 小时前
Python爬虫常用框架
开发语言·爬虫·python
excel4 小时前
用 TensorFlow.js Node 实现猫图像识别(教学版逐步分解)
前端
IMER SIMPLE4 小时前
人工智能-python-深度学习-经典神经网络AlexNet
人工智能·python·深度学习