Search code examples
pythonreactjsflask

Python(Flask)-Method Not Allowed The method is not allowed for the requested URL


I am new to flask, i just picked it up for a school project, basically i did some calculations in python and am supposed to link it whit a react front end. whenever i run the Python(Flask) code and paste the url http://127.0.0.1:5173/api/calculate_feed i get a 405 error Here is the python code

from flask import Flask, request, jsonify
from flask_cors import CORS
from ListGenration import get_feedstuff_for_hardcoded_animal

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

@app.route('/api/calculate_feed', methods=['POST'])
def calculate_feed():
    data = request.get_json()

    # Check if 'animal_type' is provided in the request
    if 'animal_type' not in data or 'purpose' not in data:
        return jsonify({'error': 'Invalid request. Missing animal_type or purpose.'}), 400

    animal_type = str(data['animal_type'])
    stage = str(data['purpose'])

    # Get the suitable feedstuff for the chosen animal type
    feedstuff_info = get_feedstuff_for_hardcoded_animal(animal_type, stage)

    if feedstuff_info:
        # Prepare the response
        response = {
            "totalProtein": feedstuff_info.get('Estimated_Protein', 0),
            "totalEnergy": feedstuff_info.get('Estimated_Energy', 0),
            "totalFiber": feedstuff_info.get('Estimated_Fiber', 0)
        }

        return jsonify(response), 200
    else:
        return jsonify({'error': f'No feedstuff information available for {animal_type} in {stage} stage.'}), 404

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

and here is the react code(the part that makes a request and takes the response)Note: i did not write this code the front end developer did and am don't know react

 const handleAnimalClick = (item) => {
    // Use Axios for API request
    setActions({ ...actions, purpose: item })
    axios.post('/api/calculate_feed', { animal_type: selectedAnimal, purpose:item })
      .then(response => {
        const data = response.data;
        console.log('Nutritional Information:', data);

        // Update the state with the received nutritional information
        setTotalProtein(data.totalProtein || 'Daily');
        setTotalEnergy(data.totalEnergy || 'Daily');
        setTotalFiber(data.totalFiber || 'Daily');
      })
      .catch(error => {
        console.error('Error fetching nutritional information:', error);
      });
     
   
  };

I don't know what a doing wrong, i am running the flack in a Virtual Environment (venv) ...\GDSC_Project\Python_Files python server.py

  • Serving Flask app 'server'
  • Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
  • Running on http://127.0.0.1:5173 Press CTRL+C to quit
  • Restarting with stat
  • Debugger is active!
  • Debugger PIN: 125-115-080

and am running the react code simultaneously VITE v5.0.12 ready in 458 ms

➜ Local: http://localhost:5173/ ➜ Network: use --host to expose ➜ press h + enter to show help

What i tried

  • CHANGING the flask port to match that of react host
  • Running the flask in a virtual environment
  • Enabled CORS for all routs

Solution

  • Looks to me like you might be misunderstanding a few basics. Some important fundamentals:

    • When you run Flask, you are running a web server that will answer TCP requests on the port you indicate. If you want to interact with your flask app, you need to be sure the request goes to 127.0.0.1:5173 (or whatever your port is).
    • When you enter an address in your browser and hit enter, you are performing a GET. If you are trying to access that API endpoint directly in your browser, you will have a method problem because your route explicitly states it is limited to "POST"
    • When you run the development server for react, you are running a different web server on a different TCP port. If you expect to be accessing react-generated content, you probably want to see 127.0.0.1:12345 (or whatever your react port is) in your browser address bar. You cannot run multiple servers on the same port number
    • When you make requests from JS, using a relative URL like you do here: axios.post('/api/calculate_feed',, the browser assumes you want to talk to the same server as the one hosting the page. In other words, you may want to try being explicit about the server, ie try axios.post('http://127.0.0.1:5173/api/calculate_feed', and use that to better understand what your problem is.

    In summary, your browser is probably not talking to the server process you think you are talking to AND/OR you are inadvertently using an HTTP method that is not defined (you need to define a route to cover GET).

    Check these details carefully and see if that leads to your solution.