django+vue實現(xiàn)跨域的示例代碼
版本
Django 2.2.3
Python 3.8.8
djangorestframework 3.13.1
django-cors-headers 3.11.0
django實現(xiàn)跨域
說明:此處方法為后端解決跨越,即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', # 子應(yīng)用
]
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提供的數(shù)據(jù)接口,安裝axios
npm install axios -S
4. 前端vue配置axios插件,修改src/main.js
... import axios from 'axios'; // 添加: 導入axios包 // axios.defaults.withCredentials = true; // 允許ajax發(fā)送請求時附帶cookie Vue.prototype.$axios = axios; // 把對象掛載vue中 ···
5. 在XX.vue中跨域請求數(shù)據(jù)
···
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>到此這篇關(guān)于django+vue實現(xiàn)跨域的文章就介紹到這了,更多相關(guān)django vue跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue/cli3.0腳手架部署到nginx時頁面空白的問題及解決
這篇文章主要介紹了vue/cli3.0腳手架部署到nginx時頁面空白的問題及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
vue3中vue.config.js配置Element-plus組件和Icon圖標實現(xiàn)按需自動引入實例代碼
這篇文章主要給大家介紹了關(guān)于vue3中vue.config.js配置Element-plus組件和Icon圖標實現(xiàn)按需自動引入的相關(guān)資料,在Vue 3中可以通過配置vue.config.js文件來進行按需自動引入,需要的朋友可以參考下2024-02-02
vue-router嵌套路由方式(頁面路徑跳轉(zhuǎn)但頁面顯示空白)
這篇文章主要介紹了vue-router嵌套路由方式(頁面路徑跳轉(zhuǎn)但頁面顯示空白),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-04-04
Vue3+TypeScript實現(xiàn)PDF預(yù)覽組件
這篇文章主要為大家詳細介紹了如何基于Vue3+TypeScript實現(xiàn)PDF預(yù)覽組件,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-04-04

