Search code examples
flaskhttp-status-code-405

Method Not Allowed.The method is not allowed for the requested URL. On Flask


Used the following in cmd:

    set FLASK_APP=hello_app.py
    flask run --host=0.0.0.0

code: '''

<input id="name-input" type="text"/>
<button id="name-button">Submit</button>
<p id="greeting"></p>

<script href="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $('#name-button').click(function(event){
        let message = {
            name: $('#name-input').val()
        }
        $.post('http://192.168.1.106:5000/hello', JSON.stringify(message), function(response){
            $('#greeting').text(response.greeting);
            console.log(response);
        });
    });
</script>

'''

    from flask import Flask
    from flask import jsonify
    from flask import request

    app = Flask(__name__)
    @app.route('/hello', methods=['POST'])
    def hello():
        message = request.get_json(force=True)
        name = message['name']
         response = {
            'greeting':'Hello,' + name + '!'
        }
        return jsonify(response)

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

Got 405 error while running. Already tried adding 'GET' to the methods which led to Bad Request instead. Can anybody please help?


Solution

  • Change the methods to ['GET','POST']

    @app.route("/home",methods=['GET','POST'])
    

    THEN handle the post data by

    if request.method=='POST':
        #handle post data here
    else:
        #return a normal page
        return "home"
    

    also change the last if 'name' == 'main': to this if __name__ == '__main__':

    EDIT: add your jsonify code in the handle post data section