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

React前端表单无法向Flask后端发送POST请求问题求助

问题核心原因
  • 你的HTML表单未指定action属性,默认向当前页面根路径/发起POST请求,但Flask后端仅在/post路径注册了POST方法,没有处理/路径POST请求的逻辑,因此触发方法不允许的报错。
  • 原生表单默认提交行为会触发页面刷新,不符合React单页应用的交互逻辑,也无法正常接收后端返回的JSON数据做后续处理。
  • 你写的<input type="variable">属于无效属性,input不存在variable类型,属于不规范写法。
修复方案

方案1:修改原生表单配置(仅适合不需要局部刷新的场景,会触发页面刷新)

直接给form标签补充action和enctype属性,同时修正input的type属性:

<form method="post" action="http://localhost:5000/post" enctype="multipart/form-data">
  <label>Input</label>
  <input type="text" name="variable" />
  <input type="submit" value="Submit" />
</form>

方案2:React异步提交方案(推荐,适配单页应用交互逻辑)

前端代码修改

使用useState管理表单输入,阻止表单默认提交行为,通过fetch异步发送请求:

import { useState } from 'react'

function App() {
  const [inputValue, setInputValue] = useState('')

  const handleSubmit = async (e) => {
    e.preventDefault()
    const formData = new FormData()
    formData.append('variable', inputValue)
    try {
      const response = await fetch('http://localhost:5000/post', {
        method: 'POST',
        body: formData
      })
      const result = await response.json()
      console.log('后端返回结果:', result)
    } catch (error) {
      console.error('请求出错:', error)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Input</label>
      <input 
        type="text" 
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <input type="submit" value="Submit" />
    </form>
  )
}

后端补充配置

如果之前没有配置跨域,需要安装flask-cors处理前后端不同端口的跨域问题:

  1. 安装依赖:
    pip install flask-cors
  2. 启用跨域:
from flask import Flask, request, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app) # 全局允许跨域请求

@app.route('/get',methods=['GET'])
def testGet():
        return {
            'name': 'Hello World'
        }

@app.route('/post',methods=['POST'])
def testPost():
        variable = request.form.get("variable","")
        return jsonify(variable=variable)

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

内容的提问来源于stack exchange,提问作者Justin Philip Fulkerson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 13:18:01