django 前后端分离开发解决跨域问题

django 前后端分离开发解决跨域问题

利用 django-cors-headers插件来解决前后端分离时遇到的跨域问题

第一步 安装django-cors-headers

pip install django-cors-headers

第二步 在settings.py文件中进行配置
  1. 在INSTALLED_APPS里添加"corsheaders"

    INSTALLED_APPS = [
        ...
        'corsheaders'
        ...
    ]
    
  2. 在MIDDLEWARE_CLASSES中添加配置

    MIDDLEWARE_CLASSES = (
    	...
        'corsheaders.middleware.CorsMiddleware', # 新加入的内容
        'django.middleware.common.CommonMiddleware', # 原来已经存在的项目     
        ...
    )
    
  3. 在settings.py底部添加配置

    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 = (
    	'accept',
        'accept-encoding',
        'authorization',
        'content-type',
        'dnt',
        'orgin',
        'user-agent',
        'x-csrftoken',
        'x-requested-with',
    )
    

猜你喜欢

转载自www.cnblogs.com/jiaowoxiaoming/p/12977665.html