-1

I am unable to make post request via react js to python-flask server. I am using axios. This request works on postman, but I can't seem to figure out why I can make post request from my react app.

Please see flask code:

@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

My react-redux action code:

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);
    });
};

my react class component:

  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);
  };

See below error response from 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"

Please assist

biggest_boy
  • 381
  • 4
  • 23

1 Answers1

1

The issue was that I was not sending the API parameters the right way. Since I am sending via form data I changed my code from:

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

to:

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

complete function:

  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);
    }
  };
biggest_boy
  • 381
  • 4
  • 23