How to connect the front-end Vue3 and the back-end Flask App and send data

foreword

We explained how to build a vue project and how to configure local routing in the last two articles ; this article continues to explain how to connect the front-end Vue3 and the back-end Flask App and send data.

Step 1: Modify the app.py file in flask

(assuming you have created a basic flask project by now)

  • ① Install the relevant py package in your flask project folder:
pip install flask-cors
  • ② Introduce CORS in the app.py file:
from flask_cors import CORS
  • ③ Add two lines of code:
app.config.from_object(__name__)
CORS(app, resources={
    
    r'/*': {
    
    'origins': '*'}}, supports_credentials=True)
  • Ultimately my flask code is as follows (example):
from flask import Flask, jsonify
from flask_cors import CORS

# instantiate the app
app = Flask(__name__)
app.config.from_object(__name__)

# enable CORS
CORS(app, resources={
    
    r'/*': {
    
    'origins': '*'}}, supports_credentials=True)

# sanity check route
@app.route('/')
def index():
    return


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

Step 2: Modify the Vue project code

(Assume that you have created a vue project according to the previous two articles)

  • ① Install axios (before running the npm command, make sure the current path is under the project folder)
npm install axios --save
  • ② Change the <script> section in the vue page as follows:
<script lang="ts" setup>
  import {
    
     reactive } from 'vue'
  import axios from 'axios'  //导入axios工具

  const FPath = 'http://localhost:5000/login'  //定义你要连接到flask的路由的路径
  const mqttM = reactive({
    
    
    id: '',
    ip: '',
    port: '',
    user: '',
    psw: '',
    topic:''
  })
  const onSubmit = () => {
    
    
    console.log('submit!')
    axios.post(FPath,mqttM)  // axios发送post请求到Fpath路径,mqttM是发送的数据
    	.then(res=>{
    
    console.log(res.data)})  //将从flask收到的返回值打印到控制台
} 
  </script>
  • Overall page code (example):
    insert image description here

Step 3: Start the vue project and the flask project respectively

  • Enter the address of the vue startup server in the browser, and fill in the information to submit. You can see the output in the flask project, which proves that the front-end Vue3 and the back-end Flask App have been connected.

  • Vue3 front-end page submission:
    insert image description here

  • The flask backend receives:
    insert image description here

Special Note:

What this article shows is a sample writing method that conforms to the official website of Element Plus, using typescript syntax sugar. If you do not use this syntax sugar in your project, you can refer to the following two articles: [1
] https://blog.csdn.net/ yuelizhe4774/article/details/124320679
[2] https://zhuanlan.zhihu.com/p/311510196

Guess you like

Origin blog.csdn.net/bradyM/article/details/127055497