Flask: Refresh after POST always leads to 405

Viewed 26

I have the following problem. I want to click on a button, which should perform a POST request on the Flask server using the fetch API, without refreshing the page. But when I manually refresh the page at some point, I'm always getting a 405 error. Here's the minimum code to reproduce the error:

main.py:

from flask import Flask, render_template
import json

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("index.html")


@app.route("/post", methods=["POST"])
def post_test():
    return json.dumps({"test": True})


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

The index.html file:

<script>
    async function postSomething() {
        let options = {
            method: "POST",
            body: JSON.stringify({ "name": "test" })
        }
        let request = await fetch("/post", options);
        let response = await request.json()
        console.log(response)
    }
</script>

<button onclick="postSomething()">
    Click me!
</button>

After clicking the button you get this in the console:

{test: true}

When you refresh the page afterwards you get this error in the Flask server:

127.0.0.1 - - [10/Sep/2022 12:09:52] "{"name":"test"}GET / HTTP/1.1" 405 -

For some reason, the body of the request is put before the GET? This is really strange.

0 Answers
Related