django后端解决跨域方式一Middleware
中间介实现跨域过程
1、新建中间介包
#mkidr middleware
#touch middleware/__init.py__
#vim middleware/crossdomainxhr.py
from django import http
try:
from django.conf import settings
XS_SHARING_ALLOWED_ORIGINS = settings.XS_SHARING_ALLOWED_ORIGINS
XS_SHARING_ALLOWED_METHODS = settings.XS_SHARING_ALLOWED_METHODS
XS_SHARING_ALLOWED_HEADERS = settings.XS_SHARING_ALLOWED_HEADERS
XS_SHARING_ALLOWED_CREDENTIALS = settings.XS_SHARING_ALLOWED_CREDENTIALS
except AttributeError:
XS_SHARING_ALLOWED_ORIGINS = '*'
#XS_SHARING_ALLOWED_METHODS = ['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET']
XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']
XS_SHARING_ALLOWED_CREDENTIALS = 'true'
class XsSharing(object):
"""
This middleware allows cross-domain XHR using the html5 postMessage API.
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Based off https://gist.github.com/426829
"""
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = http.HttpResponse()
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS )
response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS
return response
return None
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join( XS_SHARING_ALLOWED_METHODS )
response['Access-Control-Allow-Headers'] = ",".join( XS_SHARING_ALLOWED_HEADERS )
response['Access-Control-Allow-Credentials'] = XS_SHARING_ALLOWED_CREDENTIALS
return response
settings文件配置:
在中间介新增配置
'finance.middleware.crossdomainxhr.XsSharing',
跨域配置:
我这里前端使用的是源是http://127.0.0.1:8081
# crossdomain
#XS_SHARING_ALLOWED_ORIGINS ='*'
XS_SHARING_ALLOWED_ORIGINS = 'http://127.0.0.1:8081'
XS_SHARING_ALLOWED_METHODS = ['POST', 'GET']
XS_SHARING_ALLOWED_HEADERS = ['Content-Type', '*']
XS_SHARING_ALLOWED_CREDENTIALS = 'true'
django后端解决跨域方式二django-cors-headers
通过第三方包方式:https://github.com/ottoyiu/django-cors-headers
注意:既然有第三方包,name为什么还要用第一种方式,自己写呢?原因是第三方包对Django的版本有要求:
有些Django版本比较老的话 就只能用第一种方式咯。
具体实现如下:
1、安装django-cors-headers
pip install django-cors-headers
2、配置settings.py文件
a.在INSTALLED_APPS里添加“corsheaders”
INSTALLED_APPS = [
...
'corsheaders',
...
]
b.在MIDDLEWARE_CLASSES添加配置:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
c.在sitting.py底部添加
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
CORS_ALLOW_METHODS = (
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
'VIEW',
)
CORS_ALLOW_HEADERS = (
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
)