您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇“怎么用django+vue实现跨域”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“怎么用django+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提供的数据接口,安装axiosnpm 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>以上就是关于“怎么用django+vue实现跨域”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。