python 记录Django与Vue前后端分离项目搭建
参考链接:
https://blog.csdn.net/liuyukuan/article/details/70477095
1. 安装python与vue
2. 创建Django项目
django-admin startproject ulb_manager
3. 进入项目并创建名为backeng的app
-
cd ulb_manager
-
python manage.py startapp backend
4. 使用vue-cli创建vue项目 frontend
vue-init webpack frontend
5.打包vue目录
-
cd frontend
-
npm install
-
npm run build
打包完成后会生成dist文件 内有index.html和文件夹static
6.配置Django指向index.html
配置ulb_manager/urls.py文件
-
-
from django.views.generic import TemplateView // 添加
-
-
urlpatterns = [
-
path('admin/', admin.site.urls),
-
path('index/', TemplateView.as_view(template_name="index.html")), // 添加
-
]
配置ulb_manager/settings.py文件
-
TEMPLATES = [
-
{
-
'BACKEND': 'django.template.backends.django.DjangoTemplates',
-
# 'DIRS': [],
-
'DIRS': ['frontend/dist'], // 添加
-
'APP_DIRS': True,
-
'OPTIONS': {
-
'context_processors': [
-
'django.template.context_processors.debug',
-
'django.template.context_processors.request',
-
'django.contrib.auth.context_processors.auth',
-
'django.contrib.messages.context_processors.messages',
-
],
-
},
-
},
-
]
-
-
STATICFILES_DIRS = [ // 添加
-
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
-
-
from . import views
-
-
urlpatterns = [
-
path('testapi', views.testapi, name='testapi'),
-
]
修改backend目录下views.py文件
-
from django.shortcuts import render
-
-
# Create your views here.
-
from django.http import HttpResponse
-
import json
-
-
# 解决前端post请求 csrf问题
-
from django.views.decorators.csrf import csrf_exempt
-
-
-
def testapi(request):
-
print(request)
-
print(request.method)
-
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")
-
else:
-
print(request.POST)
-
print(request.body)
-
str1=str(request.body, encoding = "utf-8")
-
data=eval(str1)
-
print(data)
-
print(data['aa'])
-
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
-
-
-
urlpatterns = [
-
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文件
-
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',
-
]
-
-
CORS_ORIGIN_ALLOW_ALL = True // 添加
10. 在vue中请求接口
配置axios
https://blog.csdn.net/qq_39785489/article/details/80111141
在组建中使用
-
import {post,get,patch,put} from '../http'
-
-
export default {
-
name: 'HelloWorld',
-
mounted() {
-
// get('http://localhost:8000/api/testapi?aa=bb')
-
// .then((response) => {
-
// console.log(response)
-
// })
-
post('http://localhost:8000/api/testapi',{"aa": 'bb'})
-
.then((response) => {
-
console.log(response)
-
console.log(response.data.main)
-
})
-
},
-
data () {
-
return {
-
msg: 'Welcome to Your Vue.js App'
-
}
-
}
-
}
请求成功