因为项目准备从angular改为vue,涉及到一部分跨域请求问题
- 安装django-cors-headers
ps:django-cors-headers最新版支持django1.11+版本,低于1.11+版本请自行降低版本
pip install django-cors-headers
- 添加应用:
INSTALLED_APPS = (
...
'corsheaders',
...
)
- 中间件处理,注意放在第一条,第一时间进行处理:
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
...
]
- 配置访问规则或白名单
# 允许所有域名跨域(优先选择)
CORS_ORIGIN_ALLOW_ALL = True
# 或配置白名单:
# CORS_ORIGIN_WHITELIST = (
# '*'
# # '127.0.0.1:8000',
# # 'localhost:8000',
# # '127.0.0.1:8080',
# # 'localhost:8080',
# # 'ads-cms-api.aataotao.com:8000' #
# # 'taoduoduo-test.oss-cn-shenzhen.aliyuncs.com:80', # 线上
# # '10.0.2.187:8080' # 本地
# )
- 配置跨域允许方法
# 配置可用方法
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
# 允许HEADERS
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
'Pragma',
)
- 允许携带cookie:
CORS_ALLOW_CREDENTIALS = True