安装
pip install django-cors-headers
注册应用
INSTALLED_APPS = ( ... ‘corsheaders‘, ... )
中间层设置
MIDDLEWARE = [ ... ‘corsheaders.middleware.CorsMiddleware‘, ‘django.middleware.common.CommonMiddleware‘, ... ]
添加白名单
# CORS 设置跨域域名 CORS_ORIGIN_WHITELIST = ( ‘127.0.0.1:8080‘, ‘localhost:8080‘, ‘www.xxxx.com:8080‘, ‘api.xxxx.com:8000‘ )
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie ALLOWED_HOSTS = [‘www.xxxx.com:8080‘,‘api.xxxx.com:8000‘,‘127.0.0.1‘] # 前端需要携带cookies访问后端时,需要设置withCredentials: true
设置允许访问的方法( 已测,没用 )
CORS_ALLOW_METHODS = ( ‘GET‘, ‘POST‘, ‘PUT‘, ‘PATCH‘, ‘DELETE‘, ‘OPTIONS‘ )
设置允许的header:(未测)
CORS_ALLOW_HEADERS = ( ‘x-requested-with‘, ‘content-type‘, ‘accept‘, ‘origin‘, ‘authorization‘, ‘x-csrftoken‘ )
原文地址:https://www.cnblogs.com/Skyda/p/10267359.html
时间: 2024-10-03 22:45:53