React请求Django登录校验后控制台无响应输出问题求助
问题排查与修复
先给你梳理几个关键问题,对应修改后应该就能在控制台看到响应内容了:
1. React输入框状态绑定错误
邮箱输入框的value绑成了writerLoginData.writer_name,但你的状态里根本没这个字段,应该改成writerLoginData.writer_email。这个错误会导致输入的邮箱内容没法同步到状态里,最后发请求时邮箱参数是空的,触发Django异常,而React这边又没正确捕获错误,自然看不到输出。
修改后的邮箱输入框:
<Form.Control value={writerLoginData.writer_email} onChange={handleChange} name="writer_email" type="email" placeholder="Enter email" />
2. Axios异常捕获没用对
你用try/catch包了axios.post,但axios.post是异步Promise,try/catch抓不到Promise的错误,得改用.catch()或者async/await配合try/catch。
改法一:用.catch()捕获错误
const submitForm = () => { const writerLoginFormData = new FormData(); writerLoginFormData.append('writer_email', writerLoginData.writer_email) writerLoginFormData.append('writer_password', writerLoginData.writer_password) axios.post(BASE_URL, writerLoginFormData) .then((res) => { console.log('响应内容:', res.data) // 注意Django返回的是{bool: true},不是直接true if(res.data.bool === true) { localStorage.setItem('writerLoginStatus', true) // 这里要小写location,大写的Location是构造函数,不是当前窗口的地址对象 window.location.href = "/writer-dashboard"; } }) .catch((error) => { console.error('请求出错:', error) // 打印错误响应详情,方便排查 console.error('错误详情:', error.response?.data) }) }
改法二:用async/await
const submitForm = async () => { const writerLoginFormData = new FormData(); writerLoginFormData.append('writer_email', writerLoginData.writer_email) writerLoginFormData.append('writer_password', writerLoginData.writer_password) try { const res = await axios.post(BASE_URL, writerLoginFormData) console.log('响应内容:', res.data) if(res.data.bool === true) { localStorage.setItem('writerLoginStatus', true) window.location.href = "/writer-dashboard"; } } catch (error) { console.error('请求出错:', error) console.error('错误详情:', error.response?.data) } }
3. Django视图没处理异常
Writer.objects.get()找不到数据时会直接抛DoesNotExist异常,你的代码没捕获这个异常,会返回500错误,而不是预期的{'bool': False}。得加异常捕获:
修改后的Django视图:
from django.http import JsonResponse from .models import Writer from django.core.exceptions import ObjectDoesNotExist @csrf_exempt def WriterLoginDetails(request): if request.method == 'POST': # 用get方法避免参数不存在时抛KeyError writer_email = request.POST.get('writer_email') writer_password = request.POST.get('writer_password') try: writerData = Writer.objects.get(writer_email=writer_email, writer_password=writer_password) print('data found') return JsonResponse({'bool': True}) except ObjectDoesNotExist: print('no data found') return JsonResponse({'bool': False}) # 处理非POST请求 return JsonResponse({'error': '只接受POST请求'}, status=400)
4. 可选优化:改用JSON发送数据
你没上传文件,用FormData没必要,直接发JSON更简单,还能避免Django解析FormData的问题:
React端改JSON发送
const submitForm = async () => { try { const res = await axios.post(BASE_URL, writerLoginData, { headers: { 'Content-Type': 'application/json' } }) console.log('响应内容:', res.data) if(res.data.bool === true) { localStorage.setItem('writerLoginStatus', true) window.location.href = "/writer-dashboard"; } } catch (error) { console.error('请求出错:', error) console.error('错误详情:', error.response?.data) } }
Django端解析JSON数据
因为用了application/json头,request.POST拿不到数据,得从request.body解析:
import json from django.http import JsonResponse from .models import Writer from django.core.exceptions import ObjectDoesNotExist @csrf_exempt def WriterLoginDetails(request): if request.method == 'POST': try: data = json.loads(request.body) writer_email = data.get('writer_email') writer_password = data.get('writer_password') except json.JSONDecodeError: return JsonResponse({'error': 'JSON格式错误'}, status=400) try: writerData = Writer.objects.get(writer_email=writer_email, writer_password=writer_password) print('data found') return JsonResponse({'bool': True}) except ObjectDoesNotExist: print('no data found') return JsonResponse({'bool': False}) return JsonResponse({'error': '只接受POST请求'}, status=400)
5. 其他小问题
- 组件返回的JSX里,邮箱部分的
<Form.Group>标签没闭合,得补全,不然组件渲染会报错。 - 跨域问题:如果React跑在3000端口,Django在8000端口,必须给Django装
django-cors-headers并配置允许跨域,不然浏览器会拦截请求,网络面板里会显示请求被阻止。
按上面的步骤改完,再打开浏览器控制台和网络面板,就能看到请求和响应内容了。
内容的提问来源于stack exchange,提问作者Mubi Rai
相关产品推荐
相关产品推荐

