zoukankan      html  css  js  c++  java
  • Vue学习笔记djangocorsheaders安装解决跨域问题

    一  使用环境: windows 7 64位操作系统

    二  jango-cors-headers安装解决跨域问题(后端解决方案)

    • 跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。
    • 所谓同源是指,域名,协议,端口均相同,不明白没关系,举个栗子:
    • http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)
    • http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)
    • http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)
    • http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)
    • http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)
    • 127.0.0.1:8000与127.0.0.1:8001(端口不同,跨域)
    • 请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。
    • 浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。

    1.查看文档: https://github.com/adamchainz/django-cors-headers

    2.按装: python -m pip install django-cors-headers

    3.添加到setting的app中

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',  # admin依赖
        'django.contrib.contenttypes',  # admin依赖
        'django.contrib.sessions',  # admin依赖
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'corsheaders',  # 跨域设置4-(1-2):按装,注册跨域包(django-cors-headers),中间件中注册
    ]

    4.添加中间件

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'corsheaders.middleware.CorsMiddleware',  # 跨域设置4-3:跨域中间件,要放到csrf中间件前面
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    
    ] 

    5.setting下面添加下面的配置

    # 跨域设置4-4:添加跨域设置
    # 指明在跨域访问中,后端是否支持对cookie的操作
    CORS_ALLOW_CREDENTIALS = True
    # 允许所有 跨域请求
    CORS_ORIGIN_ALLOW_ALL = True
    # 白名单
    CORS_ORIGIN_WHITELIST = ()
    CORS_ALLOW_METHODS = ('DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'VIEW',)
    CORS_ALLOW_HEADERS = (
        'XMLHttpRequest',
        'X_FILENAME',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'origin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
        'Pragma',
        'x-token',
    )
    # 跨域设置4-4:添加跨域设置end

    6.文档通过浏览翻译成中文

     

  • 相关阅读:
    通过修改manifest文件来解决Vista/Win7/Win8/win10下应用程序兼容性问题
    windows下django开发环境配置
    Django网站实例效果
    手动下载Linux安装包perf
    【Nginx】负载配置
    【VIM】常用命令
    【CentOS7】SCP服务器间传文件
    【CentOS7】目录统计du命令
    【CentOS7】安装GraphicsMagick
    【Nginx】限流配置
  • 原文地址:https://www.cnblogs.com/djtang/p/13699374.html
Copyright © 2011-2022 走看看