Django Vue Js Axios已被CORS策略阻止

14ifxucb  于 2023-06-05  发布在  iOS
关注(0)|答案(2)|浏览(537)

我使用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
  • 在url的末尾添加/

当我使用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"

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)
  })

},

这是来自网络选项卡

的响应
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'),
    ]
bweufnob

bweufnob1#

不同的端口被视为CORS的不同域,请使用https://github.com/zestedesavoir/django-cors-middleware并在设置中设置CORS_ORIGIN_ALLOW_ALL = True
在Vue中删除header的设置,默认的header将起作用。你只是从Vue到Django发出CORS请求,而不是从Django到Vue。如果你从另一个域向Vue发出CORS请求,你只需要设置这些头。

jq6vz3qz

jq6vz3qz2#

正确的答案是在django后端的www.example.com中设置CORS_ALLOWED_ORIGINSsettings.py。将其指向Vue前端url(生产中的更改),
backend/settings.py

...
CORS_ALLOWED_ORIGINS =[
    'http://localhost:8000', #backend url
    'http://localhost:8080' #frontend url
]
...

然后将axios.baseURL设置为后端URL。
frontend/src/main.js变为:

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
axios.defaults.baseURL = "http://127.0.0.1:8000" //backend url
createApp(App).use(store).use(router, axios).mount('#app')

有了这些变化,它应该会起作用。不要在生产环境中关闭CORS并更改这些URL。

相关问题