1. 搭建前端+后端开发框架
1. 说明
本篇博客主要介绍网页开发中,搭建前端和后端开发框架的具体步骤,框架中所使用的技术栈如下:
前端:VUE + Javascript
后端:Python + Flask + Mysql
其中MySQL主要用来存储需要的数据,在本文中搭建基本框架时不做说明,后续该专栏系列的文章会根据情况做简要介绍。前端框架使用的是VUE2版本,读者可以根据需要换成VUE3.
该专栏系列文章需要读者具备基本的前后端开发知识,一些基本的操作可能在文章中会一笔带过。
2. 框架搭建步骤
2.1. 后端框架搭建
后端框架选择使用Python结合Flask,比较简单,在具备Python开发环境后,新建一个main.pay文件即可,具体代码如下:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
# 添加一个路由函数,用于前端通信测试 (这里的语法不懂的可以百度下)
@app.route(‘/helloFlask/<string:testPara>’, methods = [‘GET’,’POST’])
def hlloFlask(testPara):
print(“testPara : ”, testPara)
return jsonify({
‘satus’ : ‘success’,
’message’ : testPara
}),200
if __name__ == ‘__main__’:
app.run(host = ‘0.0.0.0’, debug = True)
运行此代码,会在终端里输出一些提示,其中有一个是Runing on http://127.0.0.1:5000,这里的网址需要记住,会在前端配置中使用到。到此,一个简单的后端Flask框架就已经搭建完毕。
2.2. 前端框架搭建
第一步:在前端框架搭建之前,需要做一个基本的VUE环境配置,并新建一个基于VUE2的项目,这些可以自行百度。打开项目,找到vue配置文件vue.config.js,按照如下代码进行配置:
const { defineConfig } = require(‘@vue/cli-service’)
module.exports = defineConfig({
transpileDependencies: true,
devServer:{
proxy:{
‘/api’:{
target:’http://127.0.0.1:5000’ //注意:这里的地址就是在上一步后端显示的地址
//target:’http://local host:5000’ //这样写也是可以的
changeOrigin:true,
pathRewrite:{
‘^/api’:’’
}
}
}
},
})
第二步:因为使用的是路由视图,所以需要在App.vue文件中添加路由占位符,代码如下:
<template>
<div id=“app”>
<router-view></router-view>
</div>
</template>
<script>
export default {
name:’App”,
}
</script>
<style>
</style>
第三步:在main.js文件中渲染主界面文件App.vue,代码如下:
import Vue from ‘vue’;
import App from ‘./App.vue’;
import router from ‘./router’;
new Vue({
el:’#app’,
render: h => h(App),
router,
});
第四步:创建第一个视图页面firstPage.vue,后面这个页面会被渲染到App.vue代码的路由占位符中,具体代码如下:
<template>
<div>
<span>这是第一个页面</span>
<button @click=“testFlask”>测试后端</button>
</div>
</template>
<script>
import axios from ‘axios’;
export default {
name:’first_page’,
data(){
return {
testPara:”123456”,
}
},
created(){
},
computed:{
},
wach:{
},
methods:{
testFlask(){
//注意:helloFlask是在后端定义的路由函数名,后面的是传递的参数
axios.get(‘/api/helloFlask/${this.testPara}’)
.then(response => {
if(response.data.status === ‘success’){
alert(response.data.message);
}
else{
alert(response.data.message);
}
})
},
},
}
</script>
<style scoped>
</style>
第五步:上面创建了一个子视图界面后,需要告诉路由router这个子视图是属于哪一个路由占位符的,所以还需要在index.js文件中进行指定,具体代码如下:
import Vue from “vue”;
import VueRouter from “vue-router”;
Vue.use(VueRouter);
const router = new VueRouter({
mode:”history”,
routes:[
{
path:”/“,
name:”firt_page”,
component: () => import(“@/components/firstPage.vue”)
},
],
});
至此,一个完整的前后端开发的基本框架已经搭建完毕,打开终端,输入*** npm run serve***,运行前端代码后,即可看到弹窗提示,显示出参数“123456”。