You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确构建供React读取的登录用户JSON响应接口

解决方案

问题根源

  • 第一个报错UnboundLocalError:代码进入异常分支时仅定义了status未定义data,但返回时直接引用了未赋值的data变量。
  • 第二个报错CustomUser matching query does not exist:请求时后端识别不到登录用户,request.user为匿名用户,id值为空,自然无法匹配到用户记录。
  • 浏览器直接访问接口正常、React请求失败:浏览器访问时会自动携带当前域名下的登录session cookie,而React默认发起跨域请求时不会携带cookie,导致后端无法识别登录状态。

后端Django修复

第一步:修正视图逻辑

def user_details_view(request, *args, **kwargs):
    # 先校验登录状态,未登录直接返回401
    if not request.user.is_authenticated:
        return JsonResponse({"message": "未登录,请先完成身份验证"}, status=401)
    # request.user本身就是当前登录的CustomUser实例,无需额外查询
    try:
        data = request.user.serialize()
        status = 200
    except:
        data = {"message": "用户信息获取失败"}
        status = 404
    return JsonResponse(data, status=status)

第二步:补充CORS配置(settings.py)

确保你已经安装django-cors-headers,并添加以下配置:

# 允许跨域携带cookie
CORS_ALLOW_CREDENTIALS = True
# 允许的前端源地址,替换为你实际的React服务地址
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3000',
    'http://127.0.0.1:3000',
]

前端React修复

核心是开启请求携带cookie的配置,修改后的请求代码如下:

import { useState, useEffect } from 'react';

function loadUserInfo(callback){
  const xhr = new XMLHttpRequest();
  const method = 'GET';
  const url = "http://127.0.0.1:8000/userdetails/";
  const responseType = "json";
  xhr.responseType = responseType;
  xhr.open(method, url);
  // 关键配置:允许跨域请求携带cookie
  xhr.withCredentials = true;
  xhr.onload = function(){
    console.log("接口响应:",xhr.response)
    callback(xhr.response, xhr.status)
  }
  xhr.onerror = function(){
    callback({"message":"请求发送失败"}, 400)
  }
  xhr.send();
}

function App() {
  const [info, setInfo] = useState(null)
  const [errorMsg, setErrorMsg] = useState(null)

  useEffect(()=>{
    const myCallBack = (response,status)=>{
      console.log(response,status)
      if (status === 200){
        setInfo(response)
        setErrorMsg(null)
      } else {
        setErrorMsg(response?.message || "获取用户信息失败")
      }
    }
    loadUserInfo(myCallBack)
  },[])

  // 渲染示例,可根据需求调整
  return (
    <div className="App">
      {errorMsg && <p style={{color: 'red'}}>{errorMsg}</p>}
      {info && (
        <div>
          <h3>当前登录用户信息</h3>
          <p>用户名:{info.username}</p>
          <p>邮箱:{info.email}</p>
          {/* 此处可继续渲染你serialize方法返回的其他字段 */}
        </div>
      )}
    </div>
  );
}

注意事项

  • 该方案基于Django默认的Session认证机制,要求用户必须先在同域名下登录后才能正常获取用户信息。
  • 生产环境部署时如果使用HTTPS,需要将SESSION_COOKIE_SECURE设为True,跨域场景可将SESSION_COOKIE_SAMESITE设为None。

内容的提问来源于stack exchange,提问作者Ran123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 22:18:02