时间:2022-12-16 09:32:02 | 栏目:vue | 点击:次
Django 2.2.3
Python 3.8.8
djangorestframework 3.13.1
django-cors-headers 3.11.0
说明:此处方法为后端解决跨越,即django端解决跨越。
django-cors-headers
库pip install django-cors-headers
项目/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端配置完毕
axios
访问后端django提供的数据接口,安装axios
npm install axios -S
axios
插件,修改src/main.js
... import axios from 'axios'; // 添加: 导入axios包 // axios.defaults.withCredentials = true; // 允许ajax发送请求时附带cookie Vue.prototype.$axios = axios; // 把对象挂载vue中 ···
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>