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

如何从React端访问Django REST Framework(DRF)提供的API接口?

问题解决步骤

核心原因:你使用Django的Session认证机制,跨域请求默认不会携带身份Cookie,同时未配置跨域资源共享规则,导致DRF无法识别用户登录状态返回403。

第一步:配置Django跨域支持

  • 安装依赖包:pip install django-cors-headers
  • 修改项目settings.py配置:
    INSTALLED_APPS = [
        # 其他原有app
        'corsheaders',
    ]
    
    MIDDLEWARE = [
        # 放到最顶部,优先级最高
        'corsheaders.middleware.CorsMiddleware',
        # 其他原有中间件
        'django.middleware.common.CommonMiddleware',
    ]
    
    # 允许携带Cookie
    CORS_ALLOW_CREDENTIALS = True
    # 替换为你React服务的实际访问地址,不要加末尾斜杠
    CORS_ALLOWED_ORIGINS = [
        "http://127.0.0.1:3000",
        "http://localhost:3000",
    ]
    

第二步:修改React请求代码,开启Cookie携带

在xhr.open之后添加xhr.withCredentials = true配置,修改后完整代码如下:

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("This is the response: ",xhr.response)
    callback(xhr.response, xhr.status)
  }
  xhr.onerror = function(){
    callback({"message":"The request was an error"}, 400)
  }
  xhr.send();
}

额外优化提示

你现有DRF视图代码中except块里有两行return,第二行return Response(data.data, status=status)永远不会执行,可以直接删除冗余代码。

以上配置完全适配你的场景:依赖Django自带的Session机制,不同浏览器的登录状态独立,不会互相干扰,不需要额外处理Token逻辑。

内容的提问来源于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 11:24:03