前言:上回做完了前端像后端表单传递数据,现在轮到后端传递数据
实现效果
前后端都要运行哦
一. 配置说明:
需要axios库,DjangoRestFramework,django,vue-cli,django-cors-headers
1.Vue安装:代理门
2.django安装:代理门
3.axios安装及注册:
npm install axios
注册
//main.ts
import axios from 'axios'
var app = createApp(App);
app.config.globalProperties.$url = 'http://127.0.0.1:8000/';
app.config.globalProperties.$axios = axios;
app.use(router).mount('#app')
4.drf,corsheaders安装及注册
pip install djangorestframework
pip install django-cors-headers
注册
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'toResponse', # 你注册的app 名称
'corsheaders', # 加上
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', #加上
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', # 注释掉
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
二.Vue 端设立组件getAxios
1.设立index.vue 作为views文件
1.views内容
// HTML部分
<template>
<div>
<get-axios/>
</div>
</template>
// js 部分
<script>
import getAxios from '../components/getAxios';
export default {
components: {
getAxios // 使用getAxios组件
},
data() {
return {
}
}
}
</script>
2.在router 中定义
//router目录下的 index.ts
import index from '@/views/index.vue'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'index',
component: index,
},
]
3.在components 中新建文件 getAxios.vue
//HTML部分
<template>
<div >
<button class="btn btn-primary" v-on:click="initCourse()">getaxios</button>
</div>
</template>
// js部分
<script>
export default {
name: "getAxios",
data() {
return {
file: {}, // 文件对象,最终会上传到该对象中
}
},
methods: {
initCourse:function(){
var that = this; // 在axios 中this指向会变,将vm 对象用that保留
console.log(that.$url + "course/") // 显示 http://127.0.0.1:8000/course/
this.$axios.request({
url:that.$url + "course/",
method:"GET"
}).then(function(ret){
//ajax请求发送成功后获取的请求
console.log( ret.data);
that.file = ret.data;
return ret.data;
}).catch(function(ret){
//失败或者异常之后的内容
console.log(ret)
})
}
}
}
</script>
三.django 端进行响应
1.settings 剩余准备工作(ps: rear 是我的项目根目录,toResponse是实现响应的app)
# settings.py
import os
# 下面这些话放在文件末尾
JSON_FILE_PATH = os.path.join(BASE_DIR , 'rear\json') # 定义读取文件的路径
# 设立白名单 运行http://localhost:8080 端访问
CORS_ORIGIN_WHITELIST = [
'http://localhost:8080',
]
2.在 rear 文件夹下的rear 文件夹中放置你的json文件夹,里面放置自己的json文件(有点小绕)
3.views准备工作
# toResponse 下的 views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import JsonResponse
from rear import settings
# Create your views here.
class DataTest(APIView):
def get(self, request, *args, **kwargs):
data = getjson()
return JsonResponse(data,safe=False)
def getjson():
files = []
with open(settings.JSON_FILE_PATH + "\红楼梦.json","r",encoding='utf-8') as f:
data = f.read() # 读取该目录下的红楼梦.json文件,可自己改
return data
4.urls 放置
# rear目录下的 urls.py
from django.contrib import admin
from django.urls import path
from toResponse import views
urlpatterns = [
path('admin/', admin.site.urls),
path('course/', views.DataTest.as_view()),
]