Django CORS跨域支持

服务端安装跨域组件

复制代码
pip install django-cors-headers

添加子应用,settings/dev.py,代码:

python 复制代码
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'corsheaders', # cors跨域子应用
    
    'home',  # apps已经在上面加入到python的系统导包路径列表了,这里还是出现背景颜色,原因是python虽然找到home,pycharm不知道。所以可以鼠标右键,设置apps为mark as source root
]

注册CorsMiddleware中间件【必须写在第一个位置】,settings/dev.py,代码:

python 复制代码
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # cors跨域的中间件
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

添加客户端访问服务端的白名单,设置允许哪些客户端客户端跨域访问服务端,settings/dev.py,代码:

python 复制代码
# CORS的配置信息: 
# 方案1:
# CORS_ORIGIN_WHITELIST = (
#     'http://www.leshen.cn:3000',
# )
# CORS_ALLOW_CREDENTIALS = False  # 不允许ajax跨域请求时携带cookie

# 方案2:
CORS_ALLOW_ALL_ORIGINS = True
相关推荐
geovindu几秒前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
闲云lazycloud2 分钟前
第 1 课:Harness 与 Agent 运行时
人工智能·后端
import_random6 分钟前
[python]conda和pip(区别和联系2)
python
熊哈哈O_o15 分钟前
260+异构同步链路:DDL语法自动翻译在大规模数据同步中的实现原理
后端
Aurorar0rua17 分钟前
CS50 x 2024 Notes Python - 01
开发语言·python·学习方法
用户66026761187941 分钟前
备注接口返回成功,数据库却没变:怎样限定一次修复的范围?
python
用户98883218717442 分钟前
别把 IOptionsSnapshot 注入单例:从生命周期看 .NET 配置读取
后端
姜鱼问生44 分钟前
别再 chmod 777 了,用 ACL 给它开一扇窗
后端·算法·架构
Dumbness1 小时前
用 Python + UI Automation 读写微信 PC 版:一个群消息自动回复程序的实现与踩坑
python
仿生joe会梦见漫天的大雪吗1 小时前
CTF Misc 工具选型指南:按题型分类的工具、原理与限制
后端·安全