前端
快速搭建vue项目可参考此处
var code = “a55526e8-b87b-4ff9-a8f4-43b93512a6f2”
request.js
使用axios请求,提供request服务
import axios from "axios"
const service = axios.create({
baseURL: "/api",
timeout: 50000
})
// before any request, use this config
service.interceptors.request.use(
config => {
//for future use
return config;
},
error => {
// 全局请求失败处理,当请求发送失败时,处理error
console.log(error)
}
)
export default service
data.js
根据上层提供的request服务封装成js函数实现特定的功能(向/request/ 发送post请求)
import request from '@/utils/request'
export function register (name, passwd) {
return request({
url: '/register/',
method: 'post',
data: {
name: name,
passwd: passwd
}
})
}
vue.config.js 文件
配置代理,解决跨域问题
module.exports = {
devServer: {
proxy: {
'/api': {
port: '3000',
target: 'http://localhost:8000',
changeOrigin: true,
ws: true,
pathRewrite: {
'^/api': ''
}
}
}
}
}
页面js
以vue界面为例(其实并无太多差异)
<template>
<div id="app">
<div>
<p>
If Element is successfully added to this project, you'll see an
<code v-text="'<el-button>'"></code>
below
</p>
<el-button>el-button</el-button>
</div>
<HelloWorld style="width: 200px;height: 200px;" msg="Welcome to Your Vue.js App"/>
</div>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
name: 'app',
components: {
HelloWorld
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
index.js 路由
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
}
]
const router = new VueRouter({
routes
})
export default router
Django
models.py 实体类
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
passwd = models.CharField(max_length=100)
views.py 逻辑处理
import json
from django.http import JsonResponse
def register(request):
if request.method == "POST":
json_str = request.body # 属性获取最原始的请求体数据
json_dict = json.loads(json_str) # 将原始数据转成字典格式
passwd = json_dict.get("passwd", None) # 获取 end_date
name = json_dict.get("name", None) # 获取 use_id
# 此处可进行与数据库的一系列操作
print(passwd)
print(name)
if name and passwd:
return JsonResponse({'code': 200,
'status': '注册成功!'})
else:
return JsonResponse({
'code': 1002,
'status': '数据出错!'
})
urls.py
路由
from django.contrib import admin
from django.urls import path
import trade.viewsutils.views as tv
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', tv.register)
]
为简化操作,可把setting.py中的crsf相关行注释,而只关注前后端数据的交互。