Django-服务器端对象-跨域请求

Django-服务器端对象-跨域请求

  1. 在接口函数中配置

     from django.http import HttpResponse,response,JsonResponse
     def login(request):
         todo_list = [
             {"id": "1", "content": "吃饭"},
             {"id": "2", "content": "吃饭"},
         ]
         response = JsonResponse(todo_list, safe=False)
         response["Access-Control-Allow-Origin"] = "*"
         response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
         response["Access-Control-Max-Age"] = "1000"
         response["Access-Control-Allow-Headers"] = "*"
         return response
    
  2. 安装CORS

     pip install django-cors-headers
    
  3. 添加app

     INSTALLED_APPS = (
         ...
         'corsheaders',
         ...
     )
    
  4. 添加中间件

     MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
         ...
         'corsheaders.middleware.CorsMiddleware',
         'django.middleware.common.CommonMiddleware',
         ...
     ]
    
  5. 配置允许跨站访问本站

    1. 配置允许跨站访问本站的地址

       CORS_ORIGIN_ALLOW_ALL = False
       CORS_ORIGIN_WHITELIST = (
             'localhost:63343',
       )
       
       # 默认值是全部:
       CORS_ORIGIN_WHITELIST = ()  # 或者定义允许的匹配路径正则表达式.
       
       CORS_ORIGIN_REGEX_WHITELIST = ('^(https?://)?(\w+.)?>google.com$', )   # 默认值:
       
       CORS_ORIGIN_REGEX_WHITELIST = ()
      
    2. 设置允许访问的方法

       CORS_ALLOW_METHODS = (
       'GET',
       'POST',
       'PUT',
       'PATCH',
       'DELETE',
       'OPTIONS'
       )
      
    3. 设置允许的header:

       默认值:
       
       CORS_ALLOW_HEADERS = (
       'x-requested-with',
       'content-type',
       'accept',
       'origin',
       'authorization',
       'x-csrftoken'
       )
      

猜你喜欢

转载自blog.csdn.net/ls_ange/article/details/83410579