最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

django+vue實(shí)現(xiàn)跨域的示例代碼

 更新時(shí)間:2022年03月03日 16:46:35   作者:不吃淺水魚  
在我們的項(xiàng)目中需要用到django實(shí)現(xiàn)跨域的問題,本文通過示例代碼給大家詳細(xì)介紹django+vue實(shí)現(xiàn)跨域的方法,感興趣的朋友跟隨小編一起看看吧

版本

Django 2.2.3
Python 3.8.8
djangorestframework 3.13.1
django-cors-headers 3.11.0

django實(shí)現(xiàn)跨域

說明:此處方法為后端解決跨越,即django端解決跨越。

1. 安裝 django-cors-headers 庫(kù)

pip install django-cors-headers

2. 修改項(xiàng)目配置文件 項(xiàng)目/settings.py

...
# Application definition
INSTALLED_APPS = [
    'django.contrib.staticfiles',

    'corsheaders',  # 添加:跨域組件
    'rest_framework',  # 添加:DRF框架
    'home',  # 子應(yīng)用
]
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # 添加:放首行(放其他行未測(cè)試)
    'django.middleware.security.SecurityMiddleware',
    ...
# CORS組的配置信息
CORS_ORIGIN_WHITELIST = (
    'http://127.0.0.1:8080',
    # 這里需要注意: 1. 必須添加http://否則報(bào)錯(cuò)(https未測(cè)試) 2. 此地址就是允許跨域的地址,即前端地址
)
CORS_ALLOW_CREDENTIALS = True  # 允許ajax跨域請(qǐng)求時(shí)攜帶cookie

至此django端配置完畢

3. 前端vue使用axios訪問后端django提供的數(shù)據(jù)接口,安裝axios

npm install axios -S

4. 前端vue配置axios插件,修改src/main.js

...
import axios from 'axios';  // 添加: 導(dǎo)入axios包

// axios.defaults.withCredentials = true;  // 允許ajax發(fā)送請(qǐng)求時(shí)附帶cookie
Vue.prototype.$axios = axios; // 把對(duì)象掛載vue中
···

5. 在XX.vue中跨域請(qǐng)求數(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/ 這個(gè)就是后端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實(shí)現(xiàn)跨域的文章就介紹到這了,更多相關(guān)django vue跨域內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

新疆| 藁城市| 昭觉县| 黄石市| 福泉市| 孟村| 永善县| 临武县| 壤塘县| 灵台县| 丰都县| 海丰县| 宁陵县| 岱山县| 抚宁县| 自贡市| 德惠市| 桐梓县| 建湖县| 陇川县| 林口县| 察雅县| 浦东新区| 嘉荫县| 黄平县| 牙克石市| 山丹县| 呼玛县| 水城县| 手游| 潢川县| 宁强县| 交口县| 应城市| 措美县| 调兵山市| 石棉县| 屏边| 曲沃县| 丰城市| 兴业县|