当前位置:   article > 正文

记录flask和vue的前后端交互_python vue前后端通信

python vue前后端通信

记录flask和vue的前后端交互:

python使用flask作为后端,前端使用vue框架搭建界面,使用axios方法实现前后端数据交互,一个交互的小demo


前端:

点击按钮,运行test方法,将input输入通过page传输到后端,返回的数据显示到text

  1. <input type= 'text' v-model="page" placeholder="edit me">
  2. <button @click="test()">CheckThis</button>
  3. <li>{{ text }}</li>

axios方法,传输page到后端,返回数据为res.data ,后端端口为:http://127.0.0.1:5000

  1. test(){
  2. axios.post('http://127.0.0.1:5000/test',{"name":this.page})
  3. .then(res=>{
  4. this.text = res.data; //返回数据显示到text
  5. console.log(res.data);// 返回的数据
  6. alert(this.text);
  7. })
  8. .catch(err=>{
  9. this.text = 'error' + err;
  10. })
  11. },

后端:

解决跨域问题

CORS(app, supports_credentials=True)

后端数据处理

  1. @app.route('/test', methods=['GET','post'])
  2. def test():
  3. data = request.get_json(silent=True) //获取前端数据
  4. print(data['name']) #123
  5. return jsonify('success')

 axios和ajax接收数据有区别,(Ajax的接收方法是:request.form.get(‘name’)或者直接resquest.form[‘name’])


完整程序:

hello.vue

  1. <template>
  2. <div class="hello">
  3. <input type= 'text' v-model="page" placeholder="edit me">
  4. <button @click="test()">CheckThis</button>
  5. <li>{{ text }}</li>
  6. </div>
  7. </template>
  8. <script>
  9. import axios from 'axios'
  10. export default {
  11. name: 'HelloWorld',
  12. props: {
  13. // msg: String
  14. },
  15. data(){
  16. return{
  17. text: 'null'
  18. }
  19. },
  20. methods: {
  21. test(){
  22. axios.post('http://127.0.0.1:5000/test',{"name":this.page})
  23. .then(res=>{
  24. this.text = res.data;
  25. console.log(res.data);// 返回的数据
  26. alert(this.text);
  27. })
  28. .catch(err=>{
  29. this.text = 'error' + err;
  30. })
  31. // this.text = 'nice!'
  32. },
  33. }
  34. }
  35. </script>
  36. <!-- Add "scoped" attribute to limit CSS to this component only -->
  37. <style scoped>
  38. h3 {
  39. margin: 40px 0 0;
  40. }
  41. ul {
  42. list-style-type: none;
  43. padding: 0;
  44. }
  45. li {
  46. display: inline-block;
  47. margin: 0 10px;
  48. }
  49. a {
  50. color: #42b983;
  51. }
  52. </style>

app.py

  1. from flask import Flask, jsonify, request, render_template
  2. import json
  3. from flask_cors import CORS
  4. from flask_sqlalchemy import SQLAlchemy
  5. app = Flask(__name__)
  6. CORS(app, supports_credentials=True)
  7. # 实现跨域
  8. @app.route('/test', methods=['GET','post'])
  9. def test():
  10. data = request.get_json(silent=True)
  11. print(data['name']) #123
  12. return jsonify('success')
  13. if __name__ == '__main__':
  14. app.run()

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/66546
推荐阅读
相关标签
  

闽ICP备14008679号