【问题标题】:Django Vue Js Axios has been blocked by CORS policyDjango Vue Js Axios 已被 CORS 策略阻止
【发布时间】:2020-08-27 01:14:05
【问题描述】:

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

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

我试过了:

  • Django-cors-header 及其中间件

  • Vue-axios-cors,这个有新错误

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

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

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"

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

},

这是来自网络选项卡的响应

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

【问题讨论】:

  • 您确定例外 URL 是带有前导斜杠的 http://127.0.0.1:8000/api/dashboard/login/ 吗?这可能会导致一些问题:stackoverflow.com/questions/33375797/…。另外,settings.py 中的APPEND_SLASH 的值是多少?
  • @O-9 ,是的,我做到了,我已经尝试过使用和不使用斜线,仍然得到相同的结果。我在 settings.py 中没有 APPEND_SLASH 变量。从那个链接,我认为它与我的问题不同,因为我在网络选项卡中得到响应头 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 引用者:127.0.0.1:8080/login
  • @O-9 响应头截图在帖子里,我已经更新了

标签: django vue.js django-rest-framework axios cors


【解决方案1】:

对于 CORS,不同的端口被视为不同的域,请使用 https://github.com/zestedesavoir/django-cors-middleware 并在您的设置中设置 CORS_ORIGIN_ALLOW_ALL = True

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

【讨论】:

  • 允许所有来源存在很大的安全风险。
  • @AbdRahmanAlkaff 尝试从 Vue 端删除它们不应该需要的所有标题(除了 csrf)
  • @Rehmat 这是一个安全风险,但由 OP 来决定。对于发展和学习,这不是必需的。
  • @Rehmat 感谢您的建议,一旦我部署它,我会确保这样做。但我认为这不能解决我的 Api 请求被 CORS 阻止的问题。我如何解决它?我都试过了,哈哈,我已经用谷歌搜索了好几天,这是一个错误吗?
  • 默认情况下它应该发送正确的标头,先尝试不使用它们。
猜你喜欢
  • 2021-10-13
  • 2018-07-20
  • 2021-12-25
  • 2019-08-17
  • 2019-10-01
  • 1970-01-01
  • 2020-06-02
  • 2020-05-28
  • 2021-01-07
相关资源
最近更新 更多