前端(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请求
相关推荐
.生产的驴15 分钟前
SpringBoot 消息队列RabbitMQ 消费者确认机制 失败重试机制
java·spring boot·分布式·后端·rabbitmq·java-rabbitmq
躺平的花卷19 分钟前
Python爬虫案例六:抓取某个地区某月份天气数据并保存到mysql数据库中
数据库·爬虫·python·mysql
虚拟搬运工21 分钟前
Python类及元类的创建流程
开发语言·chrome·python
姚*鸿的博客26 分钟前
pinia在vue3中的使用
前端·javascript·vue.js
学步_技术44 分钟前
Python编码系列—Python原型模式:深克隆与高效复制的艺术
开发语言·python·原型模式
宇文仲竹1 小时前
edge 插件 iframe 读取
前端·edge
Kika写代码1 小时前
【基于轻量型架构的WEB开发】【章节作业】
前端·oracle·架构
Desire.9841 小时前
Python 数学建模——灰色关联度分析
python·数学建模·灰色关联度
苹果酱05671 小时前
一文读懂SpringCLoud
java·开发语言·spring boot·后端·中间件
小鹿( ﹡ˆoˆ﹡ )1 小时前
Python中的树与图:构建复杂数据结构的艺术
开发语言·python