首页 > 编程技术 > js

django+vue实现跨域的示例代码

发布时间:2022-3-3 20:56 作者:不吃浅水鱼

版本

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接口
···

代码

<template>
  <div class="div1">
      <el-carousel trigger="click" height="600px">
        <el-carousel-item v-for="book in book_list" :key="book.index">
          <a :href="book.link" rel="external nofollow" >
            <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>

到此这篇关于django+vue实现跨域的文章就介绍到这了,更多相关django vue跨域内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

原文出处:https://www.cnblogs.com/fengzi-2016/p/15960555.html

标签:[!--infotagslink--]

您可能感兴趣的文章: