Search code examples
python-3.xgoogle-chromeflaskroutesurl-routing

Why is Google Chrome appending a forward slash to my flask url when there is none?


While testing my Flask-based web app on various browsers, I found out that Chrome browser appends a "/" after one of of my routes and only one. This behavior results in a page not found error since my routes is like this:

/dictionary

But Chrome renders is like this:

/dictionary/

Which according to flask is not the same thing.

Here is my /dictionary route and method:

@app.route("/dictionary", methods=["GET", "POST"])
def dictionary():
    results = []
    if request.method == 'POST':
        word = request.form.get("word")
        # do stuff here
        return render_template("results", results=results)
    return render_template("dictionary.html")

My html url:

<a href="{{url_for(dictionary)}}"> </a>

It generates the following expected url:

<a href="/dictionary"></a>

Please notice that this strange behavior is only noticed on Chrome browser. It works fine on Opera, Firefox, and EI. And more strangely it's only on this one route. Other routes with similar methods and url building act normal. N.B: I could change my route to "/dictionary/" so it works, but I wish to preserve "/url_example" like routes. Thank you in advance.


Solution

  • The "/" character is a forward slash. Said this, strict_slashes, which requires that the URL has a trailing slash if set, or requires that the URL does not have a trailing slash otherwise, is enabled by default, causing this issue.

    You can disable strict slashes in your entire app by doing:

    app = Flask(__name__)
    app.url_map.strict_slashes = False
    

    You can learn more about this from this answer: https://stackoverflow.com/a/33285603