Vue和Flask通信的實現
這里我們通過axios來連接Vue前端和Flask后端,使用AJAX請求進行通信。使用如下命令安裝
npm install axios
axios的使用格式:
import axios from ’axios’; export default { data: function () { return {serverResponse: ’res_test’ }; }, methods: { getData() {// 設置對應python的接口,這里使用的是localhost:5000const path = ’http://127.0.0.1:5000/getMsg’;// 這里要使用 res =>表示返回的數據axios.get(path).then(res => { // 這里服務器返回response為一個json對象 // 通過.data來訪返回的數據,然后在通過.變量名進行訪問 // 可以直接通過response.data取得key-value var msg = res.data.msg; this.serverResponse = msg; // 因為不能直接使用this作為指針,因此在這之前將this賦給了then指針 alter(’Success’ + response.status + ’,’ + response.data + ’,’ + msg); // 成功后顯示提示}).catch(error => { console.error(error);}); } }, }代碼及演示前端代碼
對./components/HelloWorld.vue文件進行改寫。代碼如下:
<!-- html部分 --><template> <div> <span>{{ serverResponse }}</span> <!--這里使用{{}}來引用JavaScript中賦給this的值--> <button @click='getData'>get data</button> </div></template><!-- js部分 --><script> import axios from ’axios’; export default { data: function () { return {serverResponse: ’res_test’ }; }, methods: { getData() {// 設置對應python的接口,這里使用的是localhost:5000const path = ’http://127.0.0.1:5000/getMsg’;axios.get(path).then(res => { // 這里服務器返回response為一個json對象 // 通過.data來訪返回的數據,然后在通過.變量名進行訪問 // 可以直接通過response.data取得key-value var msg = res.data.msg; this.serverResponse = msg; // 因為不能直接使用this作為指針,因此在這之前將this賦給了then指針 alter(’Success’ + response.status + ’,’ + response.data + ’,’ + msg); // 成功后顯示提示}).catch(error => { console.error(error);}); } }, }</script><!-- css部分 --><!-- Add 'scoped' attribute to limit CSS to this component only --><style scoped> h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; }</style>
這里主要實現了通過單擊按鈕來和服務器端進行交互獲得數據并傳回前端,將得到的數據重新來對前端進行渲染。
得到如上頁面之后,我們單擊get date按鈕,就會像后端發送GET請求,后端服務器監聽到請求之后就會返回對應的數據。
from flask import Flaskfrom flask import jsonifyfrom flask_cors import CORSapp = Flask(__name__)cors = CORS(app, resources={r'/getMsg': {'origins': '*'}})@app.route(’/’)def hello_world(): return ’test!’# 監聽127.0.0.1:5000/getMsg請求@app.route(’/getMsg’, methods=[’GET’, ’POST’])def home(): response = {’msg’: ’Hello, Python !’ } return responseif __name__ == ’__main__’: app.run()
到此這篇關于Vue和Flask通信的實現的文章就介紹到這了,更多相關Vue和Flask通信內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
