Django Vue Js Axios 已被 CORS 政策屏蔽

Abd*_*aff 2 django cors django-rest-framework vue.js axios

我使用 Django 作为后端,Vue 作为前端,我使用 axios 从 Vue 向 Django 发出请求。

我知道有很多关于此的问题,我已经尝试了所有方法,如果我没有,我不会发布问题,我已经在谷歌上搜索了大约 4 个小时,但仍然被 cors 政策阻止。 被 cors 政策阻止

我试过了:

  • Django-cors-header 及其中间件

  • Vue-axios-cors,这个出现了新错误

  • 添加标头 Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers、Access-Control-Allow-Credentials
  • 在url末尾添加/

当我使用 fiddler 检查它时,POST 请求变成选项,我不知道发生了什么。

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"
Run Code Online (Sandbox Code Playgroud)

登录.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)
  })

},
Run Code Online (Sandbox Code Playgroud)

这是网络选项卡的响应 在此输入图像描述

设置.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'),
    ]
Run Code Online (Sandbox Code Playgroud)

Air*_*ith 5

不同的端口被视为 CORS 的不同域,请使用https://github.com/zestedesavoir/django-cors-middlewareCORS_ORIGIN_ALLOW_ALL = True在您的设置中进行设置

删除 Vue 中的标题设置,默认标题将起作用。您只是从 Vue 向 Django 发出 CORS 请求,而不是从 Django 向 Vue 发出 CORS 请求。如果您从另一个域向 Vue 发出 CORS 请求,则只需设置这些标头。

  • 允许所有来源是一个很大的安全风险。 (3认同)