django+vue实现跨域

版本

Django 2.2.3
Python 3.8.8
djangorestframework 3.13.1
django-cors-headers 3.11.0

django实现跨域

说明:此处方法为后端解决跨越,即django端解决跨越。

1. 安装 django-cors-headers

pip install django-cors-headers

2. 修改项目配置文件 项目/settings.py

...
# Application definition
INSTALLED_APPS = [
    'django.contrib.staticfiles',

    'corsheaders',  # 添加:跨域组件
    'rest_framework',  # 添加:DRF框架
    'home',  # 子应用
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # 添加:放首行(放其他行未测试)
    'django.middleware.security.SecurityMiddleware',
    ...
]

...
# CORS组的配置信息
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8080',
    # 这里需要注意: 1. 必须添加http://否则报错(https未测试) 2. 此地址就是允许跨域的地址,即前端地址
)
CORS_ALLOW_CREDENTIALS = True  # 允许ajax跨域请求时携带cookie

...

至此django端配置完毕

3. 前端vue使用axios访问后端django提供的数据接口,安装axios

npm install axios -S

4. 前端vue配置axios插件,修改src/main.js

...
import axios from 'axios';  // 添加: 导入axios包

// axios.defaults.withCredentials = true;  // 允许ajax发送请求时附带cookie
Vue.prototype.$axios = axios; // 把对象挂载vue中
···

5. 在XX.vue中跨域请求数据

···
    created: function() {
      // 获取轮播图
      this.$axios.get("http://127.0.0.1:8000/book/").then(response => {
        console.log(response.data)
        this.banner_list = response.data
      }).catch(response => {
        console.log(response)
      })
     // http://127.0.0.1:8000/book/ 这个就是后端django接口
···
点击查看代码







你可能感兴趣的:(django+vue实现跨域)