has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is

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

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第1张图片
按照图示操作设置前端
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第2张图片
按照图示操作设置后端

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第3张图片

INSTALLED_APPS = [
‘django.contrib.admin’,
‘django.contrib.auth’,
‘corsheaders’,
‘rest_framework’,
‘users.apps.UsersConfig’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
]

CORS

CORS_ORIGIN_WHITELIST = (
‘http://127.0.0.1:8080’,
‘http://localhost:8080’,
‘http://www.meiduo.site:8080’,
‘http://api.meiduo.site:8000’,
‘http://www.meiduo.site’, # 添加
)
CORS_ALLOW_CREDENTIALS = True # 允许携带cookie

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’,
]
ALLOWED_HOSTS = [’*’]

另一种方法:

在Django的settings中设置如下

has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第4张图片
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第5张图片
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is_第6张图片

# 跨域增加忽略
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',
)
#部署到云服务上必备
ALLOWED_HOSTS = ['*']

你可能感兴趣的:(Django,Python)