zoukankan      html  css  js  c++  java
  • 前端报被CORS策略阻止,Django开启跨域解决

    一、问题描述

     二、解决方法

    1.安装django-cors-headers

    pip install -i https://pypi.douban.com/simple django-cors-headers

    2.将corsheaders添加到settings.py文件的INSTALLED_APPS中,尽量放在前面

    INSTALLED_APPS = [
        'corsheaders',
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'rest_framework',
        'drf_yasg'
    ]

    3.添加中间件

    需要添加在CommonMiddleware中间件之前

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'corsheaders.middleware.CorsMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

    4.添加白名单

    # CORS_ORIGIN_ALLOW_ALL为True,指定所有域名(ip)都可以访问后端接口,默认为False
    CORS_ORIGIN_ALLOW_ALL = True

    也可以通过白名单列表添加指定的ip或域名

    # CORS_ORIGIN_WHITELIST指定能够访问后端接口的ip或域名列表
    CORS_ORIGIN_WHITELIST = [
        'http://127.0.0.1:8080',
        'http://localhost:8080',
        'http://192.168.6.23:8080'
    ]

    5.允许跨域时携带Cookie

    # CORS_ALLOW_CREDENTIALS允许跨域时携带Cookie,默认为False
    CORS_ALLOW_CREDENTIALS = True

    6.验证结果

  • 相关阅读:
    Discuz利用百度ping把我们网站自动提交到百度
    正则表达式速查表1
    thinkphp 新浪新闻采集代码演示
    php采集一网站的精美图片
    百度知道的php爬虫
    新浪新闻采集程序
    mysql pid文件丢失解决办法
    js位运算-按位非
    mysql表损坏解决方案
    h5新API之WebStorage解决页面数据通信问题
  • 原文地址:https://www.cnblogs.com/xiaogongjin/p/13380440.html
Copyright © 2011-2022 走看看