【问题标题】:400 bad Request using axios, flask and react使用 axios、flask 和 react 的 400 错误请求
【发布时间】:2020-09-30 19:16:28
【问题描述】:

我无法通过 react js 向 python-flask 服务器发出发布请求。 我正在使用 axios。此请求适用于邮递员,但我似乎无法弄清楚为什么我可以从我的 react 应用发出发布请求。

请查看烧瓶代码:

@app.route('/match_home_types', methods=['GET', 'POST'])
def match_home_types():
    area = request.form['area']

    response = jsonify({
        'home_types': util.match_area_with_types(area)
    })

    response.headers.add('Access-Control-Allow-Origin', '*')

    return response

我的 react-redux 操作代码:

export const matchHouseTypes = (area) => (dispatch) => {
  axios
    .post("http://127.0.0.1:5000/match_home_types", area)
    .then((res) => {
      dispatch({
        type: MATCH_TYPES,
        payload: res.data.home_types,
      });
    })
    .catch((error) => {
      console.log(error.response);
    });
};

我的反应类组件:

  get_house_types = () => {
    const { selectedOption } = this.state;
    if (selectedOption == "Find a location") {
      alert("Please select a valid location");
    }
    var area = {
      area: selectedOption.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase()),
    };
    console.log("area:", area);
    this.props.matchHouseTypes(area);
  };

请参阅下面来自 axios 的错误响应:

data: "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">↵<title>400 Bad Request</title>↵<h1>Bad Request</h1>↵<p>The browser (or proxy) sent a request that this server could not understand.</p>↵"
status: 400
statusText: "Bad Request"

请帮忙

【问题讨论】:

标签: python reactjs flask react-redux axios


【解决方案1】:

问题是我没有以正确的方式发送 API 参数。由于我是通过表单数据发送的,因此我将代码更改为:

 var area = {
      area: selectedOption.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase()),
    };

到:

  const formData = new FormData();
          formData.append(
            "area",
            selectedOption.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase())
          );

功能齐全:

  get_house_types = (e) => {
    e.preventDefault();
    const { selectedOption } = this.state;
    if (selectedOption == "Find a location") {
      alert("Please select a valid location");
    } else {
      const formData = new FormData();
      formData.append(
        "area",
        selectedOption.replace(/(^\w|\s\w)/g, (m) => m.toUpperCase())
      );
      this.props.matchHouseTypes(formData);
    }
  };

【讨论】:

    猜你喜欢
    • 2020-05-24
    • 1970-01-01
    • 2019-07-24
    • 2021-04-09
    • 1970-01-01
    • 2017-11-27
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多