1. 发送简单请求:
同时满足以下两个条件的
- 请求方式为: HEAD、GET、POST
- 请求头只有:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type: (application/x-www-form-urlencoded、multipart/form-data、text/plain
后台只需要设置响应的头部: Access-Control-Allow-Origin
2. 对非简单请求进行处理:
非简单请求在正式地请求前, 都会发送一个OPTIONS预检请求,浏览器检查响应的header,决定是否同意CORS请求
- Access-Control-Allow-Origin: 允许哪些域来访问
- Access-Control-Allow-Methods:允许哪些请求方式
- Access-Control-Allow-Headers: 允许哪些请求头
- Access-Control-Allow-Credentials: 是否允许携带cookie
- Access-Control-Max-Age: 表明OPTIONS查询的有效期, 有效期内不必再次查询
后台服务器只需要设置一个拦截器, 对OPTIONS请求,检查并设置相应的header即可 以Django为例:
class CorsMiddle:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
response = self.get_response(request)
if request.method == "OPTIONS":
response['Access-Control-Allow-Headers'] = 'x-csrftoken'
response['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
response['Access-Control-Max-Age'] = 3600
response['Access-Control-Allow-Origin'] = '*'
return response
else:
return response
随后在settings.py配置MIDDLEWARE, 添加自定义middle的全路径
|