django后端跨越访问问题

先写个博客,后面我再更新手册

1.问题:页面访问时报错

Forbidden (CSRF cookie not set.): xxx

解决方法:

修改settings.py文件,注释掉

django.middleware.csrf.CsrfViewMiddleware'

2.问题:ajax跨域请求时报错

解决方法:

1、安装django-cors-headers

扫描二维码关注公众号,回复: 9063845 查看本文章
pip install django-cors-headers

 

2、配置settings.py文件

a.在INSTALLED_APPS里添加“corsheaders”
 

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

 

b.在MIDDLEWARE_CLASSES添加配置:

MIDDLEWARE = [
    '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',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

c.在sitting.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',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)

3.油猴原生脚本可以再开头加入这么一句话:

var s = document.createElement('meta');
s.setAttribute('http-equiv', 'Access-Control-Allow-Origin');
s.setAttribute('content', '*');
document.head.appendChild(s);

4.等同于在网页上加上这么一句;

<meta http-equiv="Access-Control-Allow-Origin" content="*" />
发布了115 篇原创文章 · 获赞 25 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/qq_32394351/article/details/104250309