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

倾然丶 夕夏残阳落幕 提交于 2019-12-23 04:58:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/57013906/why-is-google-chrome-appending-a-forward-slash-to-my-flask-url-when-there-is-non

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!