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

前端对接Flask后端的两个同配置API仅一个可用,如何排查?

故障核心原因
  • 后端路由参数不匹配:getprofile 路由定义时没有配置路径占位参数,但函数声明强制要求传入username位置参数,请求到达后端时直接抛出参数缺失异常,返回Flask默认错误响应,该响应没有携带CORS头,因此前端出现跨域报错,并非请求头配置问题。
  • 前端POST传参格式错误:ShowUser函数中body: JSON.stringify(username)是直接序列化字符串,不是符合要求的JSON对象结构,后端无法从request.json中读取到username字段。
  • 后端查询逻辑错误:getprofile中的查询语句filter_by(username=User.username)是将字段和自身对比,永远返回第一条用户数据,而非匹配传入用户名的记录。
  • 补充:你当前可用的LoginUser函数其实传参逻辑也存在错误,JSON.stringify(username, password)不会生成包含两个字段的JSON对象,仅会序列化第一个参数username的字符串值,后端能正常运行属于巧合。
修复方案

后端修改(app.py)

  1. 修正getprofile的函数定义,删除强制位置参数,修正查询逻辑:
@app.route("/getprofile/", methods=['GET','POST'])
def getprofile(): # 删除形参username
    username = request.json['username']
    # 修正查询条件,用传入的username匹配
    profile = User.query.filter_by(username=username).first()
    print(username, profile)
    print('got here')
    return register_schema.jsonify(profile)
  1. 建议全局配置CORS避免偶发跨域问题:安装flask-cors包后,在app初始化后加一行CORS(app)即可。

前端修改

  1. 修正ShowUser的传参格式:
static ShowUser(username) {
    return fetch(`http://localhost:5000/getprofile/`, {
      'method':'POST',
      mode: 'cors',
      headers: {
        'Content-Type':'application/json'
      },
      // 序列化对象而非单纯字符串
      body: JSON.stringify({username: username})
    })
    .then(response => {
      if(!response.ok) throw new Error('请求异常')
      return response.json()
    })
    .then(data => console.log(data))
    .catch(error => console.log('请求出错', error))
}
  1. 同步修正LoginUser的错误传参:
body: JSON.stringify({username: username, password: password})
// 或简写为 body: JSON.stringify({username, password})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 14:54:00