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'
       )
      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值