当前位置: 首页 > article >正文

React Axios + Django 跨域解决方案详解

一、Django 后端配置(Python)

1.1 安装 CORS 中间件
pip install django-cors-headers
1.2 配置 settings.py
# settings.py

# 核心配置项
INSTALLED_APPS = [
    ...
    'corsheaders',  # 新增应用
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',  # 必须放在最前
    'django.middleware.common.CommonMiddleware',
]

# 跨域配置
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",  # React开发地址
    "https://your-production-domain.com",
]

# 允许携带Cookie
CORS_ALLOW_CREDENTIALS = True

# 允许的自定义请求头
CORS_ALLOW_HEADERS = [
    'content-type',
    'authorization',
    'x-csrftoken',  # Django CSRF需要
]

# 允许的HTTP方法
CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH', 
    'DELETE',
    'OPTIONS'
]

# Cookie安全配置(生产环境必须)
SESSION_COOKIE_SAMESITE = 'None'  # 允许跨站
SESSION_COOKIE_SECURE = True      # 仅HTTPS传输
CSRF_COOKIE_SAMESITE = 'None'
CSRF_COOKIE_SECURE = True

# 生产环境域名白名单
ALLOWED_HOSTS = [
    '.your-domain.com',
    'localhost',
    '127.0.0.1'
]
1.3 视图示例(views.py)
from django.http import JsonResponse
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie  # 确保返回CSRF Token
def user_info(request):
    if request.method == 'GET':
        return JsonResponse({
   
            'username': request.user.username,
            'is_authenticated': request.user.is_authenticated
        })

二、React 前端配置(Axios)

2.1 创建 Axios 实例
// src/api/axios.js
import axios from 'axios';

const axiosInstance = axios.create({
   
  baseURL: process.env.REACT_APP_API_BASE_URL,
  withCredentials: true, // 关键配置:允许携带Cookie
  headers: {
   
    'Content-Type': 'application/json',
    'X-Requested-With': 'XMLHttpRequest'
  }
});

// 请求拦截器(添加CSRF Token)
axiosInstance.interceptors.request.use(

http://www.kler.cn/a/569155.html

相关文章:

  • 实现 Leaflet 多类型点位标记与聚合功能的实战经验分享
  • 2025最新Nginx高频面试题
  • 数据库操作命令详解:CREATE、ALTER、DROP 的使用与实践
  • C# 装箱(Boxing)与拆箱(Unboxing)
  • fastadmin 后台商品sku(vue)
  • 前后端传值响应下载文件压缩包
  • Docker入门指南:Windows下docker配置镜像源加速下载
  • 【计算机网络】TCP协议相关总结,TCP可靠性的生动讲解
  • Android Studio中gradle一栏中出现nothing to show 提示的解决方法
  • ubuntu中ollama设置记录
  • git 鼓励频繁提交commit early, commit often,用好分支,多用分支
  • 类和对象(6)——Object类、内部类
  • 大模型工程师学习日记(六):Embedding 与向量数据库
  • leetcode 598. 区间加法 II 简单
  • springboot417-基于Spring Boot的酒店后台管理系统(源码+数据库+纯前后端分离+部署讲解等)
  • ESP-WIFI-MESH组网方案,设备物联网无线交互,WiFi通信智能联动
  • c语言getchar
  • 从统计学视角看机器学习的训练与推理
  • Svelte 开发 AI 应用:高效轻量级前端框架的 AI 集成探索
  • LM studio 加载ollama的模型