(一)基于flask,构建一个后端
后端就采用flask的一般构建方法,然后用 flask-restful
构建一个接口,接口返回为json数据。
datas = [{'id': 1, 'name': 'xag', '年龄': 18}, {'id': 2, 'name': 'xingag', 'age': 19}]class UserView(Resource):"""通过继承 Resource 来实现调用 GET/POST 等动作方法"""def get(self):"""GET 请求:return:"""return {'code': 200, 'msg': 'success', 'data': datas}def post(self):# 参数数据json_data = request.get_json()# 追加数据到列表中new_id = len(datas)+1datas.append({'id':new_id,**json_data})# 返回新增的最后一条数据return {'code': 200, 'msg': 'ok', 'success': datas}# 接口的url设置为 test
api.add_resource(UserView,'/test')app.run(debug=True)
执行后,也就在本地有了一个服务端。地址为: http://127.0.0.1:5000
(二)用Vue3+axios在客户端获取数据
我们写了vue的App.vue
组件如下:
<template><div><ul>{{ info }}</ul></div>
</template><script>
import axios from 'axios';export default {name: 'MyComponent',data() {return {info: []};},mounted() {// 用get请求// let url = "/test";// axios.get('/api' + url)// .then(response => {// console.log(response)// this.info = response.data// })// .catch( error => {// console.log(error)// })// 用post请求let url = "/test";axios.post('/api' + url,{"a":1,"b":2,"c":"你好"}).then(response => {console.log(response)this.info = response.data}).catch( error => {console.log(error)})}
};
</script>
为了解决跨域请求的问题,还需要在 vue.config.js
文件设置如下:
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({transpileDependencies: true,devServer: {proxy: {'/api': {target: 'http://127.0.0.1:5000/', //接口域名changeOrigin: true, //是否跨域ws: true, //是否代理 websocketssecure: true, //是否https接口pathRewrite: { //路径重置'^/api': ''}}}}
})
效果
这样基本上就能拿到服务端的数据,也能从客户端提交数据到服务端。