【发布时间】: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