目录
1.创建django项目
1,打开PyCharm创建一个创建Django项目
django-admin startproject demo
2,进入项目根目录,创建一个 App 作为项目后端
cd demo
python manage.py startapp backend //backend就是app名称
2.配置django
1.在所创建的app(backend)中创建子路由(urls.py)
2.在刚创建的urls.py中配置接口路由
from django.conf.urls import url
from . import views
urlpatterns = [
url('all/', views.get),#'all/'是前端get对应路由 views.get是views中对应函数
]
3.将app下的路由添加到demo下的urls.py中
from django.conf.urls import url,include
urlpatterns = [
url(r'^', include('backend.urls')),
]
4.在demo下的settings.py中加入跨域访问
# INSTALLED_APPS 和 MIDDLEWARE 两个配置项setting.py文件初始化应该就是存在的
# 所以我们只需要在配置里加上就可以了
INSTALLED_APPS = [
...
'backend',#app的名字
'corsheaders', # pip install django-cors-headers 这个是为了防止跨域,具体请另查资料,我这里就不赘述了。
# 'rest_framework', # pip install djangorestframework 方便我们写后端接口
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
CORS_ORIGIN_ALLOW_ALL = True
5.在app下的views.py中写接口函数
from django.http import JsonResponse
def get(request):
return JsonResponse({'name':'python'})
6.运行django:
python manage.py runserver
3.创建Vue项目
1.进入前端存放目录,运行:
vue-init webpack front//安装中把vue-router选上,我们须要它来做前端路由
2.进入front目录,运行:
npm install //安装vue所须要的node依赖
3.安装所需包并运行vue:
npm install
npm install --save axios vue-axios
npm run dev
4.在src/下的main.js全局导入axios:
// 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'
import VueAxios from 'vue-axios'
//应用axios插件
Vue.use(VueAxios, axios)
// 配置后端路由
axios.defaults.baseURL = 'http://127.0.0.1:8000'
//将axios挂在全局上
Vue.prototype.$axios = axios
//关闭vue自带提示
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
5.在src/components新建test.vue,此时前端界面应为:
6.向接口发送请求,获取数据(test.vue中写入)
<template>
<div>{{name}}</div>
</template>
<script>
export default {
data(){
return{
name:''
}
},
methods:{
getData () {
this.$axios
.get('all/')
.then(response=> {
this.name=response.data.name
console.log(response.data)
})
},
},
mounted(){
this.getData()
}
}
</script>
7.在src/router/index.js下给写好的vue配置路由:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import test from '@/components/test'
Vue.use(Router)
export default new Router({
// 启用history模式(默认为hash)
model: 'history',
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/test',
name: 'test',
component: test
}
]
})