A simple implementation of front-end and back-end interaction (axios)

backend-python :

          Receive the audio file sent by the front end using axios (take the audio file as an example)

This code is a Flask application. When a POST request is received, the audio file is obtained from the request, saved to the specified path on the server, and a successful upload message is returned. Among them, response.headers['Access-Control-Allow-Origin'] = '*'this line is set to allow cross-domain access. If there is no such line, the front end will encounter cross-domain problems when uploading files, because by default, Flask only allows requests under this domain name, and if you want to make cross-domain requests, you need to set it.

from flask import Flask, request, jsonify
import os
app = Flask(__name__)
# 指定可以访问的目录
app.config['UPLOAD_FOLDER'] = os.path.abspath(os.path.dirname(__file__))

@app.route('/uplode', methods=['POST'])
def upload_audio():
    file = request.files.get('audio')
    if not file:
        return jsonify({'message': '请选择一个音频文件'}), 400

    # 保存音频文件到服务器上的某个路径
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))
    response = jsonify({'message': '上传成功'})
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response, 200

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

Front-end Vue3:

 1. vite.config.js configuration

          Projects are operations performed on the same computer. This is a Vite configuration file, where fileURLToPathand URLare modules from the Node.js standard library that convert URLs to file paths. In this configuration file, fileURLToPathand are used to point the alias URLin the project to the directory, and Vite's development server is configured to forward the request to , so that when requesting in the front-end code , it will be proxied to@srchttp://127.0.0.1:5000//xxxhttp://127.0.0.1:5000/xxx

import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  server:{
    proxy:{
      '/api': {
        target: 'http://127.0.0.1:5000/',
        changeOrigin: true,
        // 后端服务器路径不存在api路径,所以要去掉
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    }
  }
})

2. Set proxy, axios package, api decoupling:

          request.js is defined under the project utils/api

import axios from 'axios';

//1. 创建axios对象
const service = axios.create();

//2. 请求拦截器
service.interceptors.request.use(config => {
  return config;
}, error => {
  Promise.reject(error);
});

//3. 响应拦截器
service.interceptors.response.use(response => {
  //判断code码
  return response;
},error => {
  return Promise.reject(error);
});

export default service;

         audio.js is defined under the project utils/api

import request from './request'
export function audio(data){
    return request({
        url:'/api/uplode',
        method:'post',
        data,
        headers:{
            'Content-Type': 'multipart/form-data'
        }
    })
}

3、uploadAudio.vue

In scriptthe tag, we import the methods of axiosand . Here is used to get the file input box and bind it to the variable. Click the upload button to trigger the function to convert the selected file into FormData format and send it to the server by POST. At the same time, the response information returned by the server is printed on the console.vuerefrefaudioFileuploadFileaudioFile

It should be noted that in your Flask server code, you need to add cross-domain request settings to allow cross-domain access for Vue3 applications.

<template>
    <form action="" class="form">
        <input type="file" accept="audio/*" ref="audioFile">
        <button type="button" @click="uploadFile">上传音频</button>
    </form>
</template>
<script setup>
import { ref } from 'vue'
import { audio } from '../utils/api/audio';
let audioFile = ref(null)
const uploadFile = () =>{
    let file = audioFile.value.files[0]
    if(!file){
        console.error('请输入文件');
        return
    }
    const formDate = new FormData();
    formDate.append('audio',file);
    audio(formDate).then(res=>{
        console.log(res.data.message);
    }).catch(error=>{
        console.log(error);
    })
}
</script>
<style scoped>
</style>

Guess you like

Origin blog.csdn.net/m0_61998604/article/details/130560819