django-cors-headers的作用
将跨源资源共享 (CORS) 标头添加到响应的 Django 应用程序。这允许从其他来源向您的 Django 应用程序发出浏览器内请求。
1. 安装django-cors-headers
pip install django-cors-headers
2. 添加到应用程序中
INSTALLED_APPS = [
... ,
"corsheaders" ,
... ,
]
3. 在中间键中监听响应
CorsMiddleware 需要放在第一位,如果不放在第一位,可能会造成某些请求没有添加CORS
MIDDLEWARE = [
"corsheaders.middleware.CorsMiddleware" ,
"django.middleware.common.CommonMiddleware" ,
... ,
]
4. 设置访问白名单
CORS_ORIGIN_WHITELIST = (
'http://xxx.com',
'https://xxx.com',
'127.0.0.1:8080',
'localhost:8080',
)
5. 设置允许携带cookie
CORS_ALLOW_CREDENTIALS = True
6. 默认请求头列表。
CORS_ALLOW_HEADERS = [
"accept" ,
"accept-encoding" ,
"authorization" ,
"content-type" ,
"dnt" ,
"origin" ,
"user-agent" ,
"x-csrftoken" ,
"x-requested-with" ,
]