django前后端分离开发(四)——前端请求后端数据
1、django后端创建一个app
python manage.py startapp testapp
2、新app的view.py添加视图函数
import json
import time
from django.http import HttpResponse
from django.shortcuts import render
def testapp(request):
Datetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
res = {'now time': Datetime}
return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json,charset=utf-8')
3、新app添加urls.py文件并新增如下内容
from django.urls import path
from . import views
urlpatterns = [
path('index', views.testapp),
]
4、新app的urls.py注册到项目urls里
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='index.html')),
path('testapp/', include("testapp.urls")),
]
5、后端访问http://127.0.0.1:8000/testapp/index,网页显示如下内容表示后端模拟数据成功
6、安装django-cors-headers
pip install django-cors-headers
7、配置setting文件
ALLOWED_HOSTS = [
'127.0.0.1' # 添加这行
]
CORS_ORIGIN_ALLOW_ALL = True # 添加这行
CORS_ALLOW_CREDENTIALS = True # 添加这行
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware', # 添加这行(注意顺序)
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
8、npm安装axios
npm install axios vue-axios --save
9、vue项目main.js添加如下内容
import axios from 'axios'
import VueAxios from "vue-axios";
axios.defaults.baseURL='http://127.0.0.1:8000';
Vue.use(VueAxios,axios)
10、前端项目src/components添加test.vue
<template>
<div>
<p>{{ message }}</p>
<p><input type="text" placeholder="请输入内容" v-model="params"></p>
<p><button @click="test">确定</button></p>
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
message: 'hello',
params: '123456789123'
}
},
methods:{
test:function (){
this.axios.get('/testapp/index').then((res)=>{
this.message=res.data
})
}
}
}
</script>
<style scoped>
</style>
11、在前端项目的src/Router的index.js里添加分路由
import Test from '@/components/test'
{
path: '/test',
name: 'Test',
component: Test
}
12、功能验证,点击图中的确定按钮,界面中的hello变成后端提供的数据,证明前端请求后端的数据成功。