参考文档
Vue-cli3和Django本地结合教程
https://www.jianshu.com/p/1916ffe4a7b8
python 记录Django与Vue前后端分离项目搭建
https://blog.csdn.net/qq_39785489/article/details/82751868
环境
win7 64位
pycharm 2019.2
vue-cli
pycharm 创建 django 工程
点击create
运行前需要确定 8000 端口 没有被别的程序占用
创建 vue 工程:
在目录F:\vue\django\bookstore\下面执行如下操作:
在目录:F:\vue\django\bookstore\frontend
下面创建一个新文件:vue.config.js
内容为:
/* django会认static文件夹,所以没有的话需要在vue.config.js里面配置。
因为vuecli3没有vue.config.js文件,所有需要手动创建
*/
module.exports = {
// 输出目录
assetsDir: 'static',
};
修改django的setting.py文件
F:\vue\django\bookstore\bookstore\settings.py
ROOT_URLCONF = 'bookstore.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'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',
],
},
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend/dist/static"),
]
F:\vue\django\bookstore\bookstore\urls.py
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name="index.html")),
]
运行一下看看效果:
2019-12-17
继续前后端分离
在 F:\vue\django\bookstore\booklist 目录下面新建urls.py文件
F:\vue\django\bookstore\booklist\urls.py
内容为:
from django.urls import path
from . import views
urlpatterns = [
path('testapi', views.testapi, name='testapi'),
]
修改F:\vue\django\bookstore\booklist\views.py文件
from django.shortcuts import render
# Create your views here.
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
@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")
修改:F:\vue\django\bookstore\bookstore\urls.py 文件
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from django.conf.urls import url
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', TemplateView.as_view(template_name="index.html")),
path('api/', include('booklist.urls'))
]
跨域请求
这时请求Django接口可能会出现跨域问题
安装django-cors-headers
pip install django-cors-headers
修改文件:
F:\vue\django\bookstore\bookstore\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
vue中请求接口
参考文档
Vue-cli 3.x 添加axios插件
https://segmentfault.com/a/1190000020506968
vue-cli3 增加 axios插件
https://blog.csdn.net/renyi2013/article/details/89921360
修改vue.config.js
module.exports = {
assetsDir: 'static',
devServer:{
proxy:{
'/api':{
target:'http://localhost:8006',
ws:true,
changeOrigin:true
}
}
}
};
http://127.0.0.1:8006/api/testapi 这个是get
{“errorcode”: 100, “type”: “Get”, “data”: {“main”: null}}
在F:\vue\django\bookstore\frontend\src\目录
新建文件http.js
import axios from 'axios';
// import { Message } from 'element-ui';
// axios.defaults.timeout = 5000;
// axios.defaults.baseURL ='';
//http request 拦截器
axios.interceptors.request.use(
config => {
// const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
config.data = JSON.stringify(config.data);
config.headers = {
'Content-Type':'application/x-www-form-urlencoded',
}
// if(token){
// config.params = {'token':token}
// }
return config;
},
error => {
return Promise.reject(err);
}
);
//http response 拦截器
axios.interceptors.response.use(
response => {
// console.log(response)
if(response.data.errCode ==2){
// router.push({
// path:"/login",
// querry:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
// })
}
return response;
},
error => {
return Promise.reject(error)
}
)
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/
export function get(url,params={}){
return new Promise((resolve,reject) => {
axios.get(url,{
params:params
})
.then(response => {
resolve(response.data);
})
.catch(err => {
reject(err)
})
})
}
/**
* 封装post请求
* @param url
* @param data
* @returns {Promise}
*/
export function post(url,data = {}){
return new Promise((resolve,reject) => {
axios.post(url,data,
// {
// headers: {
// 'token': 'Bearer',
// }
// }
)
.then(response => {
resolve(response.data);
},err => {
reject(err)
})
})
}
/**
* 封装patch请求
* @param url
* @param data
* @returns {Promise}
*/
export function patch(url,data = {}){
return new Promise((resolve,reject) => {
axios.patch(url,data)
.then(response => {
resolve(response.data);
},err => {
reject(err)
})
})
}
/**
* 封装put请求
* @param url
* @param data
* @returns {Promise}
*/
export function put(url,data = {}){
return new Promise((resolve,reject) => {
axios.put(url,data)
.then(response => {
resolve(response.data);
},err => {
reject(err)
})
})
}
修改文件:
F:\vue\django\bookstore\frontend\src\components\HelloWorld.vue
<script>
import {post,get,patch,put} from '../http'
export default {
name: 'HelloWorld',
props: {
msg: String
},
mounted() {
// get('http://localhost:8000/api/testapi?aa=bb')
// .then((response) => {
// console.log(response)
// })
post('http://localhost:8006/api/testapi',{"aa": 'bb'})
.then((response) => {
console.log(response)
console.log(response.data.main)
})
},
}
</script>
npm run build 之后
django 方面启动
python manage.py runserver 8006
然后 chrome 浏览器输入:
http://127.0.0.1:8006/ 在按下F12 :
http://localhost:8080
页面加载的时候,会自动的发送一个post请求
工程代码:
https://download.csdn.net/download/wowocpp/12037667