欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 前端(vue3)和后端(django)的交互

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

2024/10/27 20:14:06 来源:https://blog.csdn.net/2303_79193185/article/details/140927280  浏览:    关键词:前端(vue3)和后端(django)的交互

  

vue3中: 

<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):

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 中所有异常类的基类,这个可以捕获到任意错误,同时将捕获到的异常对象赋 ereturn JsonResponse({'error': str(e)}, status=400)#404表示客户端发送了错误的请求#同时返回json格式的数据,表示是一个字典,主键是error,值是通过把e变成str类型的数据类型return JsonResponse({'error': '只接受POST请求'}, status=405)#405表示使用错误的方法https请求

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com