django 解决csrf跨域问题
django解决跨域请求的问题
方法:1
1、中间件代码
[root@linux-node01 mysite]# tree middlewares middlewares ├── base.py ├── base.pyc ├── cors.py ├── cors.pyc ├── __init__.py └── __init__.pyc 0 directories, 6 files [root@linux-node01 mysite]#
2. 代码结构
middlewares/base.py
[root@linux-node01 mysite]# cat middlewares/base.py #!/bin/env python # -*- coding: utf-8 -*- class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response [root@linux-node01 mysite]#
核心文件middlewares/cors.py
[root@linux-node01 mysite]# cat middlewares/cors.py #!/bin/env python # -*- coding: utf-8 -*- from .base import MiddlewareMixin class CORSMiddleware(MiddlewareMixin): """CORS中间件""" def process_response(self, request, response): if request.method == "OPTIONS": response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Headers'] = '*' response['Access-Control-Allow-Methods'] = '*' else: response['Access-Control-Allow-Origin'] = '*' return response [root@linux-node01 mysite]#
3. settings.py文件配置
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'mysite.middlewares.cors.CORSMiddleware' ]
方法:2
1.安装django-cors-headers
pip install django-cors-headers
2.配置settings.py文件
INSTALLED_APPS = [ 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', #这个放到第一位 ] 复制代码 CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW', ) CORS_ALLOW_HEADERS = ( 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', )
## 白名单,使用'*' 方式好像不能 CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://localhost:8000', 'http://localhost:8080', ]
复制代码
OK!问题解决!