【问题标题】:I can't send post request from react form to flask server [duplicate]我无法将发布请求从反应表单发送到烧瓶服务器 [重复]
【发布时间】:2019-10-11 01:00:07
【问题描述】:

我有一个 reactjs 作为前端,flask 服务器作为后端。我正在尝试从注册表单发送数据(使用 Formik)。当我进行发布请求时,出现错误 500。 我注意到当我使用邮递员时,一切都很好,并且烧瓶在 postgresql 中创建了新记录。

前端在http://localhost:3000/register, 后端在http://localhost:5002/adduser 我现在该怎么办?

function handleSubmit(values, actions) {

  const options = {
    headers: {
      'Content-type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Referrer-Policy': 'origin-when-cross-origin'
    },
    method: 'POST',
    mode: 'no-cors',
    body: JSON.stringify(values)
  }

fetch('http://localhost:5002/adduser', options)
    .then(response => console.log(response))
    .catch(error => console.error(error))
}
@app.route('/adduser', methods=['GET', 'POST'])
def register():
  if request.method == "POST":
    print(request.form['userName'])
    print(request.form['email'])
    data = {
      'name': request.form['userName'],
      'surname': request.form['surname'],
      'email': request.form['email'],
      'user_password': request.form['password'],
      'phone_number': request.form['phoneNumber']
    }
    mydb = Database(host=os.getenv('host'), database=os.getenv('database'), user=os.getenv('user'), password=os.getenv('password'))
    mydb.insert_data(data)

    return jsonify({'mydata': data})

    # name = request.form['name']
    # surname = request.form['surname']
    # email = request.form['email']
    # password = request.form['password']
    # phone_number = request.form['phoneNumber']
  return "<h1>Hello Flask</h1>"

if __name__ == "__main__":
    app.run(debug=True, port=5002)
    app.secret_key = os.urandom(24)

【问题讨论】:

  • 你能发布价值吗?如果您收到 500,您的服务器收到请求但有问题,很可能您发送的数据不正确。您也可以发布您使用邮递员发送的请求吗?
  • 如果我使用邮递员一切正常,但是当我尝试使用 react 时,我在控制台 (500) 中出现错误。提交后登录服务器werkzeug.exceptions.HTTPException.wrap.&lt;locals&gt;.newcls: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

标签: javascript flask fetch-api


【解决方案1】:

您无法通过 json 内容类型请求访问 request.form。

你需要更换

'Content-type': 'application/json'

'Content-Type': 'multipart/form-data'

您的 handleSubmit 函数将与此类似:

function handleSubmit(values, actions) {

let options = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    method: 'POST'
  };

  options.body = new FormData();
  for (let key in values) {
    options.body.append(key, values[key]);
  }

  fetch('http://localhost:5002/adduser', options)
    .then(response => console.log(response))
    .catch(error => console.error(error))
  }
}
}

另一种可能的解决方案是保持客户端代码不变,并通过 request.json 而不是 request.form 访问您的数据。

【讨论】:

  • 在表单提交按钮后,无法与flask建立连接
  • 尽量保持 'Content-type': 'application/json' 并用 request.json 替换 request.form
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 2023-03-11
  • 2017-09-22
  • 1970-01-01
相关资源
最近更新 更多