django 1.0 跨域问题及解决
本文只收录常见情况方式及解决方式
相信只要涉及到前后端分离的项目在本地开发费阶段都会遇到跨域问题,以下通过中间件方式处理
问题一:
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1、创建my中间件:
# -*- coding: utf-8 -*- from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse class CrossDomainFormat(MiddlewareMixin): def process_request(self, request): """解决复杂请求的跨域问题""" if request.method == 'OPTIONS': return HttpResponse(status=204) def process_response(self, request, response): # 允许你的域名来获取我的数据 response['Access-Control-Allow-Origin'] = "*" # 允许你携带Content-Type请求头 response['Access-Control-Allow-Headers'] = "Content-Type" # 告诉浏览器,缓存预检结果24小时,即针对同一URL请求,发送第一个OPTION请求往后24小时内不再发送OPTION请求。 response['Access-Control-Max-Age'] = 86400 # 允许你发送DELETE,PUT response['Access-Control-Allow-Methods'] = "DELETE, PUT" return response
2、 settings 中注册中间件
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',
# 这里 'autotest.app.my_middleware.CrossDomainFormat' ]
3、 之后重启就完成了
PS: 如果还是出现跨域问题, 请仔细检查是不是请求接口跳错了, 比如 / 问题。
问题二:
has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
这个问题一般是前端自定义header导致, 比如: 携带token
解决:(后端)
class CrossDomainFormat(MiddlewareMixin): def process_request(self, request): """解决复杂请求的跨域问题""" if request.method == 'OPTIONS': return HttpResponse(status=204) def process_response(self, request, response): # 允许你的域名来获取我的数据 response['Access-Control-Allow-Origin'] = "*" # 允许你携带Content-Type请求头, 自定义携带参数以逗号分隔 response['Access-Control-Allow-Headers'] = "Content-Type, token" # 告诉浏览器,缓存预检结果24小时,即针对同一URL请求,发送第一个OPTION请求往后24小时内不再发送OPTION请求。 response['Access-Control-Max-Age'] = 86400 # 允许你发送DELETE,PUT response['Access-Control-Allow-Methods'] = "*" return response
原因: 浏览器在发送带有自定义的请求头时, 浏览器会先向服务器发送OPTIONS预检请求, 探测该请求服务端是否允许自定义跨域字段. 如果允许,则继续执行请求, 如果不允许, 则返回错误信息提示错误.