一、Django 后端配置(Python)
1.1 安装 CORS 中间件
pip install django -cors-headers
1.2 配置 settings.py
INSTALLED_APPS = [ . . . 'corsheaders' ,
] MIDDLEWARE = [ . . . 'corsheaders.middleware.CorsMiddleware' , 'django .middleware.common.CommonMiddleware' ,
]
CORS_ALLOWED_ORIGINS = [ "http://localhost:3000" , "https://your-production-domain.com" ,
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = [ 'content-type' , 'authorization' , 'x-csrftoken' ,
]
CORS_ALLOW_METHODS = [ 'GET' , 'POST' , 'PUT' , 'PATCH' , 'DELETE' , 'OPTIONS'
]
SESSION_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SECURE = True
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
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 实例
import axios from 'axios' ; const axiosInstance = axios. create ( { baseURL : process. env. REACT_APP_API_BASE_URL , withCredentials : true , headers : { 'Content-Type' : 'application/json' , 'X-Requested-With' : 'XMLHttpRequest' }
} ) ;
axiosInstance. interceptors. request. use (