D
D
Dauren S2020-10-24 22:07:29
CORS
Dauren S, 2020-10-24 22:07:29

Cors Django+Vue?

Django Rest Framework wrote the API.
With postman the desktop works without problems.
When trying to send a request from vue.js, a CORS error occurs

Access to XMLHttpRequest at 'http://localhost:8000/api/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Although in django I did according to this instruction
https://github.com/adamchainz/django-cors-headers#...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'userprofile.apps.UserprofileConfig',
    'kindergartens.apps.KindergartensConfig',
    'rest_framework',
    'corsheaders',
]

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

ROOT_URLCONF = 'api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'api.wsgi.application'
CORS_ORIGIN_ALLOW_ALL = True

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dauren S, 2020-10-26
@dauren101

CORS_ALLOWED_ORIGINS = [
    "https://example.com",
    "http://127.0.0.1:8080",
    "http://localhost:8080",
    "http://127.0.0.1:9000"
]
CORS_ALLOW_CREDENTIALS=True

R
Ranwise, 2020-10-25
@Ranwise

try adding

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = default_headers + (
    'Access-Control-Allow-Headers',
    'Access-Control-Allow-Credentials',
    'Access-Control-Allow-Origin',
)

CORS_ORIGIN_ALLOW_ALL = True

CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',
    'http://127.0.0.1:3000',
)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question