赞
踩
python使用flask作为后端,前端使用vue框架搭建界面,使用axios方法实现前后端数据交互,一个交互的小demo
点击按钮,运行test方法,将input输入通过page传输到后端,返回的数据显示到text
- <input type= 'text' v-model="page" placeholder="edit me">
- <button @click="test()">CheckThis</button>
- <li>{{ text }}</li>
axios方法,传输page到后端,返回数据为res.data ,后端端口为:http://127.0.0.1:5000
- test(){
- axios.post('http://127.0.0.1:5000/test',{"name":this.page})
- .then(res=>{
- this.text = res.data; //返回数据显示到text
- console.log(res.data);// 返回的数据
- alert(this.text);
- })
- .catch(err=>{
- this.text = 'error' + err;
- })
- },
解决跨域问题
CORS(app, supports_credentials=True)
后端数据处理
- @app.route('/test', methods=['GET','post'])
- def test():
- data = request.get_json(silent=True) //获取前端数据
- print(data['name']) #123
- return jsonify('success')
axios和ajax接收数据有区别,(Ajax的接收方法是:request.form.get(‘name’)或者直接resquest.form[‘name’])
hello.vue
- <template>
- <div class="hello">
- <input type= 'text' v-model="page" placeholder="edit me">
- <button @click="test()">CheckThis</button>
- <li>{{ text }}</li>
- </div>
- </template>
-
- <script>
- import axios from 'axios'
- export default {
- name: 'HelloWorld',
- props: {
- // msg: String
- },
- data(){
- return{
- text: 'null'
- }
- },
- methods: {
- test(){
- axios.post('http://127.0.0.1:5000/test',{"name":this.page})
- .then(res=>{
- this.text = res.data;
- console.log(res.data);// 返回的数据
- alert(this.text);
- })
- .catch(err=>{
- this.text = 'error' + err;
- })
- // this.text = 'nice!'
- },
- }
- }
- </script>
-
- <!-- Add "scoped" attribute to limit CSS to this component only -->
- <style scoped>
- h3 {
- margin: 40px 0 0;
- }
- ul {
- list-style-type: none;
- padding: 0;
- }
- li {
- display: inline-block;
- margin: 0 10px;
- }
- a {
- color: #42b983;
- }
- </style>
-

app.py
- from flask import Flask, jsonify, request, render_template
- import json
-
- from flask_cors import CORS
- from flask_sqlalchemy import SQLAlchemy
-
- app = Flask(__name__)
- CORS(app, supports_credentials=True)
- # 实现跨域
-
-
- @app.route('/test', methods=['GET','post'])
- def test():
- data = request.get_json(silent=True)
- print(data['name']) #123
- return jsonify('success')
-
-
- if __name__ == '__main__':
- app.run()

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。