Django解决跨域问题

django在处理post请求时会报错403 Forbidden 

如何解决?

1. 在html页面form标签中添加  {% csrf_token %}

        1.1 在用ajax发送post请求时参考 django post请求 - 有腹肌的猿 - 博客园 (cnblogs.com)

2.注释中间件    'django.middleware.csrf.CsrfViewMiddleware'

 3.安装django-cors-headers

pip install django-cors-headers

配置

INSTALLED_APPS = [ #注册应用
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'django_crontab',
    'corsheaders', #增加这个
]
MIDDLEWARE = [ #中间件
    'corsheaders.middleware.CorsMiddleware', #增加这个,放最前面
    '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',

]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = () #白名单ip,可以不填

CORS_ALLOW_CREDENTIALS = True # 允许携带cookie

# 前端需要携带cookies访问后端时,需要设置
# withCredentials=True

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',
)

 

posted @ 2022-06-07 22:13  腹肌猿  阅读(134)  评论(0编辑  收藏  举报