django+vue实现跨域

博客 分享
0 197
优雅殿下
优雅殿下 2022-03-03 16:56:02
悬赏:0 积分 收藏

django+vue实现跨域

版本

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

django实现跨域

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

1. 安装 django-cors-headers

pip install django-cors-headers

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

...# Application definitionINSTALLED_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发送请求时附带cookieVue.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接口···
点击查看代码
<template>  <div >      <el-carousel trigger="click" height="600px">        <el-carousel-item v-for="book in book_list" :key="book.index">          <a :href="book.link">            <img width="80%" :src="book.image" alt="">          </a>        </el-carousel-item>      </el-carousel>  </div></template><script>  export default {    name:"Book",    data(){      return {        book_list:[]      };    },    created: function() {      // 获取轮播图      this.$axios.get("http://127.0.0.1:8000/book/").then(response => {        console.log(response.data)        this.book_list = response.data      }).catch(response => {        console.log(response)      })    }  }</script><style>.div1 {  margin-top: 100px;  height: 1000px}img {  width: auto;  height: auto;  max-width: 100%;  max-height: 100%;}</style>
让记忆空白!
posted @ 2022-03-03 16:33 不吃浅水鱼 阅读(22) 评论(0) 编辑 收藏 举报
回帖
    优雅殿下

    优雅殿下 (王者 段位)

    2018 积分 (2)粉丝 (47)源码

    小小码农,大大世界

     

    温馨提示

    亦奇源码

    最新会员