本文主要记录,我是如何使用django-cors-headers来解决跨域请求问题的
一下载django-cors-headers并在django中进行设置
1下载django-cors-headers
pip install django-cors-headers
2在setting.py中设置
#加入需要跨域请求的url,'*'为所有网页都可访问。
ALLOWED_HOSTS = ['*']
INSTALLED_APPS = [
...
#跨域请求
'corsheaders',
]
MIDDLEWARE = [
#中间件设置
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ALLOW_CREDENTIALS = True
#设置为允许所有网页跨域请求
CORS_ORIGIN_ALLOW_ALL = True
#设置允许跨域请求的网页
CORS_ORIGIN_WHITELIST = (
'127.0.0.1:8080',#3.0以下的cors不需要加http
'http://127.0.0.1:8080',#3.0以上的cors要加http
)
#设置请求方法
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
#设置请求协议
CORS_ALLOW_HEADERS = (
'XMLHttpRequest',
'X_FILENAME'