版本
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">
<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>
