天天看點

Django 配置跨域Django —— 中跨域配置 & axios

Django —— 中跨域配置 & axios

一. vue端

vue跨域配制(第一種方法)
在config檔案夾下的index.js中配制
    proxyTable: {
    '/api': {  //使用"/api"來代替"http://f.apiplus.c" 
    target: 'http://127.0.0.1:8000/', //源位址 
    changeOrigin: true, //改變源 
    pathRewrite: { 
      '^/api': '' //路徑重寫 
      } 
  } 
},

           

二. Django端

跨域(第二種方法)
用Django的第三方包 django-cors-headers 來解決跨域問題
操作步驟:
1.pip install django-cors-headers
2.在settings.py中添加'corsheaders.middleware.CorsMiddleware',在SessionMiddleware和CommonMiddleware的中間
2.1.在INSTALLED_APPS裡添加“corsheaders”
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',#新加
]
2.2.在MIDDLEWARE添加
‘corsheaders.middleware.CorsMiddleware’, ‘django.middleware.common.CommonMiddleware’
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
     'corsheaders.middleware.CorsMiddleware',#新加
     'django.middleware.common.CommonMiddleware',#新加
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
 
]
2.3.在sitting.py底部添加
#跨域增加忽略
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()
 # 對應的發送的請求的跨域
CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)
 
CORS_ALLOW_HEADERS = (
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
)



3.在settings.py中添加CORS_ORIGIN_ALLOW_ALL = True

           

三. axios用法

axios使用
axios完整寫法:
this.axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then((res)=>{
      console.log(res)
}).catch((error)=>{
      console.log(error)
 });
post請求
this.axios.post('',{}).then((res)=>{}).catch((error)=>{})
get請求
axios.get('/user?ID=12345')
.then((response)=> {
  console.log(response);
})
.catch((error)=> {
  console.log(error);
});

在main.js裡配置,該兩行
import axios from 'axios'
Vue.prototype.axios = axios   //其它元件可以使用this.axios

           

以上是django配置跨域的具體操作,可以選中在前端vue配置跨域,後端Django配置跨域都跨域,希望對同學們有所幫助