“Vue+Flask前后端传参”的版本间的差异

来自CloudWiki
跳转至: 导航搜索
Vue代码
第73行: 第73行:
 
   },
 
   },
 
   mounted () {
 
   mounted () {
    axios
+
axios
      .get('http://127.0.0.1:5000/')
+
  .get('http://127.0.0.1:5000/hello')
      .then(response => (this.info = response))
+
  .then(response => (this.info = response.data))
      .catch(function (error) { // 请求失败处理
+
  .catch(function (error) { // 请求失败处理
        console.log(error);
+
    console.log(error);
      });
+
  });
 +
 
 
   }
 
   }
 +
 
})
 
})
 
</script>
 
</script>
第87行: 第89行:
 
</nowiki>
 
</nowiki>
  
[[文件:vue2022041502.png|600px]]
+
[[文件:vue2022041604.png|600px]]
 +
 
 
==参考文档==
 
==参考文档==
  
 
参考文档:https://blog.csdn.net/weixin_47597012/article/details/108092533
 
参考文档:https://blog.csdn.net/weixin_47597012/article/details/108092533

2022年4月16日 (六) 04:12的版本

背景

学习如何接收vue的请求并将数据返回给vue显示出来

例如:一个项目需要查数据库,大家知道前端操作不安全,所以我们需要把请求发送给python后端,python后端在处理数据并把数据发送给前端

环境准备(后端)

安装Flask

pip install flask

因为存在跨域问题,需要使用flask_cors来修饰

pip install flask-cors

Flask代码

test.py:

import json
from flask import Flask
app = Flask(__name__)#创建一个该类的实例,第一个参数是应用模块或者包的名称
from flask_cors import *

@app.route('/hello')#告诉Flask 什么样的URL能触发函数
@cross_origin()
def hello_world():
    #return 'Hello World!'
    s=['张三','年龄','姓名']
    t={}
    t['姓名']='张三'
    t['年龄']='23'
    t['职业']='码农'
    data={}
    data['SUCCESS']='SUCCESS'
    data['data']=t
    return json.dumps(data,ensure_ascii=False)


if __name__ == '__main__':#程序入口
    app.run()#让应用运行在本地服务器上。
    #app.run( host='0.0.0.0') #允许任意网址访问本站

python test.py 运行这段代码

在浏览器输入http://127.0.0.1:5000/hello

如果正常,会显示如下页面:

Vue2022041603.png

Vue代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://cdn.staticfile.org/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="app">
  {{ info }}
</div>
<script type = "text/javascript">
new Vue({
  el: '#app',
  data () {
    return {
      info: null
    }
  },
  mounted () {
	axios
	  .get('http://127.0.0.1:5000/hello')
	  .then(response => (this.info = response.data))
	  .catch(function (error) { // 请求失败处理
	    console.log(error);
	  });

  }

})
</script>
</body>
</html>


Vue2022041604.png

参考文档

参考文档:https://blog.csdn.net/weixin_47597012/article/details/108092533