Implementation of communication between Vue and Flask

Implementation of communication between Vue and Flask

Install axios and implement communication

Here we use axios to connect the Vue front end and the Flask back end, and use AJAX requests to communicate. Install using the following command

npm install axios

The usage format of axios:

import axios from 'axios';
  export default {
    data: function () {
      return {
        serverResponse: 'res_test'
      };
    },
    methods: {
      getData() {
        // Set the corresponding python interface, here we use localhost:5000
        const path = 'http://127.0.0.1:5000/getMsg';
        // Here we need to use res => to represent the returned data axios.get(path).then(res => {
          // Here the server returns a response as a json object // Access the returned data through .data, and then access it through .variable name // You can directly get the key-value through response.data
          var msg = res.data.msg;
          this.serverResponse = msg; // Because this cannot be used directly as a pointer, this is assigned to the then pointer before alter('Success' + response.status + ',' + response.data + ',' + msg); // Display prompt after success }).catch(error => {
          console.error(error);
        });
      }
    },
  }

Code and Demo

Front-end code

Rewrite the ./components/HelloWorld.vue file. The code is as follows:

<!-- html part -->
<template>
  <div>
    <span>{{ serverResponse }}</span>
    <!--{{}} is used here to reference the value assigned to this in JavaScript-->
    <button @click="getData">get data</button>
  </div>
</template>
<!-- js part -->
<script>
  import axios from 'axios';
  export default {
    data: function () {
      return {
        serverResponse: 'res_test'
      };
    },
    methods: {
      getData() {
        // Set the corresponding python interface, here we use localhost:5000
        const path = 'http://127.0.0.1:5000/getMsg';
        axios.get(path).then(res => {
          // Here the server returns a response as a json object // Access the returned data through .data, and then access it through .variable name // You can directly get the key-value through response.data
          var msg = res.data.msg;
          this.serverResponse = msg; // Because this cannot be used directly as a pointer, this is assigned to the then pointer before alter('Success' + response.status + ',' + response.data + ',' + msg); // Display prompt after success }).catch(error => {
          console.error(error);
        });
      }
    },
  }
</script>
<!-- css part -->
<!-- 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>

The main implementation here is to interact with the server by clicking a button to obtain data and transmit it back to the front end, and then re-render the front end with the obtained data.

figure.1

After getting the above page, we click the get date button, which will send a GET request to the backend. After the backend server monitors the request, it will return the corresponding data.

figure.2

Client code

from flask import Flask
from flask import jsonify
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app, resources={r"/getMsg": {"origins": "*"}})


@app.route('/')
def hello_world():
    return 'test!'

# Listen for 127.0.0.1:5000/getMsg requests @app.route('/getMsg', methods=['GET', 'POST'])
def home():
    response = {
        'msg': 'Hello, Python!'
    }
    return response


if __name__ == '__main__':
    app.run()

This is the end of this article about the implementation of Vue and Flask communication. For more relevant Vue and Flask communication content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Eight examples of how Vue implements component communication
  • A very detailed summary of communication between Vue components
  • Vue3.x uses mitt.js for component communication
  • How does Vue implement communication between components?
  • Vue component communication method case summary

<<:  Solution to the paging error problem of MySQL one-to-many association query

>>:  How to read the regional information of IP using Nginx and GeoIP module

Recommend

How to compile and install opencv under ubuntu

Easy installation of opencv2: conda install --cha...

How to redirect to https through nginx load balancing

Copy the certificate and key on the web scp -rp -...

Example of customizing the style of the form file selection box

Copy code The code is as follows: <!DOCTYPE ht...

Use of nginx custom variables and built-in predefined variables

Overview Nginx can use variables to simplify conf...

Usage and demonstration of ref in Vue

ref definition: used to register reference inform...

Detailed explanation of the relationship between React and Redux

Table of contents 1. The relationship between red...

Query process and optimization method of (JOIN/ORDER BY) statement in MySQL

The EXPLAIN statement is introduced in MySQL quer...

Explanation of Truncate Table usage

TRUNCATE TABLE Deletes all rows in a table withou...

CSS navigation bar menu with small triangle implementation code

Many web pages have small triangles in their navi...

How to install vim editor in Linux (Ubuntu 18.04)

You can go to the Ubuntu official website to down...

React diff algorithm source code analysis

Table of contents Single Node Diff reconcileSingl...

Front-end JavaScript housekeeper package.json

Table of contents 1. Required attributes 1. name ...