记录Django API与Vue前端进行交互

记录Django API与Vue前端进行交互

准备工作

  • 安装Node.js

  • 写API接口

  • 解决Cors跨域

如果是偏后端的话,建议不要去深究Vue的原理,我们只要知道,前端是怎样获取数据,它的规范是啥就行了。

Vue项目目录

首先我们要熟悉创建之后的Vue项目的目录

在安装环境的里面的博客后文有介绍img

src目录是我们要开发的目录,我们只需要重点操作三个文件, main.jsindex.jsAPP.vue这三个文件。

main.js (项目入口)

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.

import Vue from 'vue'
import App from './App'
import router from './router'
import axios from "axios"

Vue.prototype.$axios = axios
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

index.js

import Vue from 'vue'
import Router from 'vue-router'

import Course from '@/components/Course'
import Micro from '@/components/Micro'
import News from '@/components/News'
import Index from '@/components/Index'
import Detial from '@/components/Detial'
Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/index',
      name: 'index',
      component: Index
    },
    {
      path: '/course',
      name: 'course',
        component: Course
    },
    {
      path: '/detail/:id',
      name: 'detail',
      component: Detial
    },
    {
      path: '/news',
      name: 'news',
      component: News
    }
  ],
  mode:'history' #将url中的#省略
})

APP.vue

<template>
  <div id="app">
    <h1>hello vue</h1>
    <router-link to="/index">首页</router-link>
    <router-link to="/course">课程</router-link>
    <router-link to="/micro">深科技</router-link>
    <router-link to="/news">新闻</router-link>
    <router-view/>
    <h3>why not display</h3>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

<router-view> 组件是一个 functional 组件,渲染路径匹配到的视图组件。<router-view> 渲染的组件还可以内嵌自己的 <router-view>,根据嵌套路径,渲染嵌套组件。

<router-link> 组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 <a> 标签,可以通过配置 tag 属性生成别的标签.。另外,当目标路由成功激活时,链接元素自动设置一个表示激活的 CSS 类名。

我们将会在 components目录下写入我们的Vue文件

Course.vue

<template>
    <div>
      <h1>{{msg}}</h1>
      <div v-for="row in courseList">
        <div style="width: 350px;float: left;">
          <img>
          <h3><router-link :to="{name:'detail',params:{id:row.id}}">{{row.title}}</router-link></h3>
          <p>{{row.level}}</p>
        </div>
      </div>

    </div>
</template>

<script>
    export default {
        name: "course",
        data() {
            return {
              msg: '课程',
              courseList:[]
            }
        },

         mounted:function(){
           // vue页面刚加载时自动执行
            this.initCourse()
        },
        methods:{
          initCourse:function(){
            //往后台发ajax请求,并获取课程列表
            //axios/jquery 用的都是xmlrequest对象
            //第一步:
            var that = this;

            this.$axios.request({
              url:"http://127.0.0.1:8000/api/book/",
              method:"GET"
            }).then(function(ret){
              //ajax请求发送成功后获取的请求
              if(ret.data.status === 0){
                console.log(ret.data.data)
                that.courseList = ret.data.data
              }else{
                alert("获取失败")
              }
            }).catch(function(ret){
              //失败或者异常之后的内容

            })

          }
  }
    }
</script>

通过 axios进行请求我们后端的API - http://127.0.0.1:8000/api/book/

我们要注意的是浏览器具有同源策略,所以当我们请求不同的域名时,我们需要在写一个中间件,加上请求头

Access-Control-Allow-Origin: http://127.0.0.1:8000/api/book/ //该字段表明可供那个源跨域
Access-Control-Allow-Methods: GET, POST, PUT        // 该字段表明服务端支持的请求方法
Access-Control-Allow-Headers: X-Custom-Header       // 实际请求将携带的自定义请求首部字段

具体代码

# author navigator
from django.middleware.common import CommonMiddleware

class MiddlewareMixin:
    def __init__(self, get_response=None):
        self.get_response = get_response
        super().__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        response = response or self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response

class Cors(MiddlewareMixin):
    def process_response(self, request, response):
        response["access-control-allow-origin"] = '*'
        return response

总结:前后端分离,我们要关注后台的书写,潜心后端,不断进步

猜你喜欢

转载自blog.csdn.net/qq_42992704/article/details/105869676
今日推荐