this afternoon, I wrote an ajax request and response method, something like this:
<script type="text/javascript">
$(function () {
$.get("{{ url_for("blueprint.api") }}", function (data) {
console.log(data.test);
});
});
</script>
@blueprint.route("/api", methods=["GET"])
def api():
return jsonify("test": "success")
to test it, I thought there would be no problem. Result:
Failed to load resource: the server responded with a status of 404 (NOT FOUND)
Why?
after some investigation, it is finally determined that the route is written incorrectly.
when using blueprints, write a statement like this:
app.register_blueprint(blueprint, url_prefix="/")
The problem lies in the parameter url_prefix . Remove this parameter and you can pass the test. However, I thought of another situation, so I retained the parameter url_prefix and modified rule :
@blueprint.route("api", methods=["GET"])
def api():
return jsonify("test": "success")
also passed the test.
when using blueprints, you can use the url_for method to get the path.
- when
url_prefix="/",rule="/api",url_formethod output/ api, the request fails (Not
Found); - when
url_prefix="/",rule="api",url_formethod output/ api, the request is successful; - when
url_prefix=Noneorurl_prefix="",rule="/api",url_formethod outputs/ api, the request is successful.
the question is, why did case 1 fail the request?
