python 记录Django与Vue前后端分离项目搭建
参考链接:
https://blog.csdn.net/liuyukuan/article/details/70477095
1. 安装python与vue
2. 创建Django项目
django-admin startproject ulb_manager
3. 进入项目并创建名为backeng的app
-
-
python manage.py startapp backend
4. 使用vue-cli创建vue项目 frontend
vue-init webpack frontend
5.打包vue目录
-
-
-
打包完成后会生成dist文件 内有index.html和文件夹static
6.配置Django指向index.html
配置ulb_manager/urls.py文件
-
-
from django.views.generic import TemplateView
-
-
-
path(‘admin/‘, admin.site.urls),
-
path(‘index/‘, TemplateView.as_view(template_name="index.html")),
-
配置ulb_manager/settings.py文件
-
-
-
‘BACKEND‘: ‘django.template.backends.django.DjangoTemplates‘,
-
-
‘DIRS‘: [‘frontend/dist‘],
-
-
-
-
‘django.template.context_processors.debug‘,
-
‘django.template.context_processors.request‘,
-
‘django.contrib.auth.context_processors.auth‘,
-
‘django.contrib.messages.context_processors.messages‘,
-
-
-
-
-
-
-
os.path.join(BASE_DIR, "frontend/dist/static"),
-
7. 这时启动Django项目 并访问/index便能打开打包好的vue项目
python manage.py runserver
8. Django添加接口
在Django的backend目录下新建urls.py文件
-
from django.urls import path
-
-
-
-
-
path(‘testapi‘, views.testapi, name=‘testapi‘),
-
修改backend目录下views.py文件
-
from django.shortcuts import render
-
-
-
from django.http import HttpResponse
-
-
-
-
from django.views.decorators.csrf import csrf_exempt
-
-
-
-
-
-
if request.method == "GET":
-
print(request.GET.get(‘aa‘))
-
resp = {‘errorcode‘: 100, ‘type‘: ‘Get‘, ‘data‘: {‘main‘: request.GET.get(‘aa‘)}}
-
return HttpResponse(json.dumps(resp), content_type="application/json")
-
-
-
-
str1=str(request.body, encoding = "utf-8")
-
-
-
-
print(type(request.body))
-
resp = {‘errorcode‘: 100, ‘type‘: ‘Post‘, ‘data‘: {‘main‘: data[‘aa‘]}}
-
return HttpResponse(json.dumps(resp), content_type="application/json")
配置ulb_manager/urls.py文件
-
from django.contrib import admin
-
from django.urls import include, path
-
from django.views.generic import TemplateView
-
-
-
-
path(‘admin/‘, admin.site.urls),
-
path(‘index/‘, TemplateView.as_view(template_name="index.html")),
-
path(‘api/‘, include(‘backend.urls‘))
-
这时接口就可以访问到了
9. 开发环境跨域
前端编辑时依旧使用npm run dev 这时请求Django接口可能会出现跨域问题
安装django-cors-headers
pip install django-cors-headers
配置ulb_manager/settings.py文件
-
-
‘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‘,
-
-
-
CORS_ORIGIN_ALLOW_ALL = True
10. 在vue中请求接口
配置axios
https://blog.csdn.net/qq_39785489/article/details/80111141
在组建中使用
-
import {post,get,patch,put} from ‘../http‘
-
-
-
-
-
-
-
-
-
post(‘http://localhost:8000/api/testapi‘,{"aa": ‘bb‘})
-
-
-
console.log(response.data.main)
-
-
-
-
-
msg: ‘Welcome to Your Vue.js App‘
-
-
-
请求成功