zoukankan      html  css  js  c++  java
  • Django解决跨域问题

    1.安装:pip install django-cors-headers

    2.修改django项目中的settings.py

    INSTALLED_APPS = [
        ...
        'corsheaders',
    ]
    
    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',  # 这个是跨域的中间件需要放在最上边,也可以在下边两个的下面,但是不能放在其他位置了
        'django.middleware.common.CommonMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        # 'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'XXX.middleware.MyCorsMiddle.MyCorsMiddle',  # 这是自己写的中间件,添加响应头
    ]
    
    # 新添以下内容
    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',
    )

    3.添加中间件来添加响应头

    就是为了在响应头内添加上Access-Control-Allow-Origin = *

    from django.utils.deprecation import MiddlewareMixin
    
    
    class MyCorsMiddle(MiddlewareMixin):
    
        def process_response(self, request, response):
            if request.method == 'OPTIONS':
                # 允许它
                response['Access-Control-Allow-Headers'] = 'Content-Type'
                # obj['Access-Control-Allow-Headers']='*'
    
            # obj['Access-Control-Allow-Origin']='http://127.0.0.1:8000'
    
            response['Access-Control-Allow-Origin'] = '*'
            return response

    开发过程中遇到的问题,有误斧正。

  • 相关阅读:
    文件操作
    苹果越狱
    猫的期幻之旅-20130114
    js传url中文参数乱码问题
    JS三元
    SQL同列合并
    数据库引擎介绍innodb和myisam
    数据库优化
    gleez 下分页功能优化
    kohana安装总结
  • 原文地址:https://www.cnblogs.com/wangpanger/p/11402373.html
Copyright © 2011-2022 走看看