You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vite前端与Flask后端同步通信问题求助

Vite + Flask 前后端通信失败的排查与修复

问题排查

  1. 函数名不匹配
    HTML按钮绑定的是sendData(),但JS中定义的函数是sendDataToPython(data),点击按钮时无法找到对应函数,导致请求无法触发。

  2. 跨域请求被拦截
    Vite默认开发服务端口为5173,Flask默认端口为5000,属于不同域名端口,浏览器会拦截跨域请求,这是交互失败的核心原因之一。

  3. 请求目标错误
    直接使用/api/data作为请求地址,会指向Vite开发服务器而非Flask后端,导致请求发错目标。

修复步骤

1. 修正函数调用匹配问题

修改JS代码,补充按钮绑定的sendData函数,获取输入框内容并调用请求函数:

async function sendDataToPython(data) {
  try {
    const response = await fetch('/api/data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({input: data})
    });

    if (response.ok) {
      const responseData = await response.json();
      console.log(responseData);
      // 可在此处添加聊天机器人返回内容的页面渲染逻辑
    } else {
      console.error('请求错误:', response.status);
    }
  } catch (error) {
    console.error('网络错误:', error);
  }
}

// 补充按钮绑定的函数
function sendData() {
  const inputBox = document.getElementById('inputBox');
  const inputValue = inputBox.value.trim();
  if (inputValue) {
    sendDataToPython(inputValue);
    inputBox.value = ''; // 发送后清空输入框
  }
}

2. 解决Flask跨域问题

安装flask-cors扩展:

pip install flask-cors

修改Flask代码,启用CORS并完善数据处理逻辑:

from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # 开发阶段允许所有跨域请求,生产环境需限制域名

@app.route('/api/data', methods=['POST'])
def receive_data():
    data = request.json
    if not data or 'input' not in data:
        return jsonify({'error': '缺少输入数据'}), 400
    # 此处可接入聊天机器人逻辑,生成对应回复
    user_input = data['input']
    response_data = {'message': f'收到你的输入:{user_input}'}
    return jsonify(response_data)

if __name__ == '__main__':
    app.run(debug=True)  # 开启debug模式,便于查看错误信息

3. 配置Vite代理(推荐)

在Vite项目的vite.config.js中配置代理,避免每次请求写完整Flask地址:

import { defineConfig } from 'vite'

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:5000',
        changeOrigin: true
      }
    }
  }
})

配置后,前端请求/api/data会自动转发到http://localhost:5000/api/data。

测试步骤

  1. 启动Flask服务:运行Python脚本,确认服务在5000端口启动。
  2. 启动Vite开发服务:在前端项目目录执行npm run dev。
  3. 在输入框输入内容,点击Send按钮,打开浏览器控制台查看请求及返回结果。

内容的提问来源于stack exchange,提问作者Syntaxm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 13:00:17