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

MySQL Innodb key features insert buffer

Table of contents What is insert buffer? What are...

Detailed explanation of Vue's hash jump principle

Table of contents The difference between hash and...

Mini Program to Implement Sieve Lottery

This article example shares the specific code of ...

MySQL SQL statement analysis and query optimization detailed explanation

How to obtain SQL statements with performance iss...

Detailed steps for implementing timeout status monitoring in Apache FlinkCEP

CEP - Complex Event Processing. The payment has n...

A brief discussion on the problem of Docker run container being in created state

In a recent problem, there is such a phenomenon: ...

Five ways to traverse objects in javascript Example code

Table of contents Prepare Five weapons for…in Obj...

How to implement Mysql switching data storage directory

How to implement Mysql switching data storage dir...

An article to understand what is MySQL Index Pushdown (ICP)

Table of contents 1. Introduction 2. Principle II...

Vue implements a shopping cart that can change the shopping quantity

This article shares with you how to use Vue to ch...

The main idea of ​​​​dynamically setting routing permissions in Vue

I have seen some dynamic routing settings on the ...

Example analysis of mysql shared lock and exclusive lock usage

This article uses examples to illustrate the usag...

Let IE6, IE7, IE8 support CSS3 rounded corners and shadow styles

I want to make a page using CSS3 rounded corners ...