亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

 更新時(shí)間:2022年03月03日 16:46:35   作者:不吃淺水魚(yú)  
在我們的項(xiàng)目中需要用到django實(shí)現(xiàn)跨域的問(wèn)題,本文通過(guò)示例代碼給大家詳細(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)跨域

說(shuō)明:此處方法為后端解決跨越,即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訪(fǎng)問(wèn)后端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)論