2

Im using Django as backend and Vue as frontend, i use axios to make a request from Vue to Django.

I know there is so many question about this, i've tried it all and wouldn't post a question if im not, i have been Googling it about 4 hours and yet still have the blocked by cors policy. blocked by cors policy

I've tried:

  • Django-cors-header, with its middleware

  • Vue-axios-cors, got new error with this one

  • Adding header Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Credentials
  • Adding / at the end of the url

When i inspect it using fiddler, the POST request become OPTIONS, i have no idea whats happening.

main.js

import Axios from 'axios'

Vue.config.productionTip = false

Vue.prototype.$http = Axios

const csrf = localStorage.getItem("csrftoken")

if (csrf){
  Vue.prototype.$http.defaults.headers.common['X-CSRFToken'] = csrf
}

Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*"
Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET, POST, PATCH, PUT, DELETE, OPTIONS"
Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, access-control-allow-origin, Authorization"
Vue.prototype.$http.defaults.headers.common['Access-Control-Allow-Credentials'] = "true"

Login.vue

login(){

  const header = {
    headers:{
     'Access-Control-Allow-Origin' : "*",
     'Access-Control-Allow-Methods' : "GET, POST, PATCH, PUT, DELETE, OPTIONS",
     'Access-Control-Allow-Headers' : "Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token, access-control-allow-origin, Authorization",
     'Access-Control-Allow-Credentials' : "true",
    }
  }

  this.$http.post('http://127.0.0.1:8000/api/dashboard/login/',{
    username: this.username,
    password: this.password,

  },header).then(function(response){
    console.log(response)
  }).catch(function(error){
    console.log(error)
  })

},

this are the response from the network tab enter image description here

settings.py

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['localhost','127.0.0.1']


# Application definition

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

    'rest_framework',
    'corsheaders',

    'dashboard',

]

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

ROOT_URLCONF = 'web.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        '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 = 'web.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CORS_ORIGIN_ALLOW_ALL = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'


STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),
    # os.path.join(BASE_DIR, 'vue'),
    ]
  • 1
    Are you sure that the excepted URL is `http://127.0.0.1:8000/api/dashboard/login/` with the leading slash? It might cause some problems: https://stackoverflow.com/questions/33375797/django-rest-framework-xmlhttprequest-cannot-load-http-127-0-0-18000-xyz-api. Also, what is the value of `APPEND_SLASH` in `settings.py`? – O-9 May 11 '20 at 13:48
  • @O-9 , yes i did, i've tried it with and without slash, still got the same result. i did not have APPEND_SLASH variable in settings.py. and from that link, i think its different from my problem cause i got response header in the network tab Accept: application/json, text/plain, */* Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, X-Auth-Token Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS Access-Control-Allow-Origin: * Content-Type: application/json;charset=UTF-8 Referer: http://127.0.0.1:8080/login – Abd Rahman Alkaff May 11 '20 at 14:12
  • @O-9 the response header screenshot is in the post, i've updated it – Abd Rahman Alkaff May 11 '20 at 14:16

1 Answers1

5

A different port is considered a different domain for CORS, use https://github.com/zestedesavoir/django-cors-middleware and set CORS_ORIGIN_ALLOW_ALL = True in your settings

Remove setting the headers in Vue, the default headers will work. You are only making CORS requests from Vue to Django, not from Django to Vue. You would only need to set these headers if you were making CORS requests from another domain to Vue.

Airith
  • 2,024
  • 1
  • 14
  • 10