Issue
I'm trying to use await fetch in JS to use a function that I created in Flask. My code for the JS is:
let dictionary = await fetch("/getName");
let user_name = await dictionary.name;
and my code in flask is:
@app.route("/getName")
def getName():
output = {"name": ""}
print("hello")
if NAME_KEY in session:
output["name"] = session[NAME_KEY]
print(output)
return jsonify(output)
why does this not work? to be specific to causes the website to have a 400 bad request.
I removed the await feature from both of the variables, and instead it creates the error:
'Request' object has no attribute 'is_xhr'
I downgraded werkzeug to 0.16.1, and no nothing just shows up. There aren't any errors, but nothing comes and nothing gets printed by the system. Here is my new code for JS. (Flask stays the same)
let dictionary = fetch("/getName");
console.log("start");
console.log(dictionary);
let user_name = dictionary.name;
Solution
Most likely you haven't wrapped the await code inside a function that has been declared with async. Or you have declared the async function incorrectly. This example works:
Your Flask view/route:
@app.route('/getName')
def get_name():
print("in getName view....")
output = {"name": ""}
return jsonify(output)
Your client side code calling the above /getName route:
<head>
<title>REST</title>
<script>
const getName = async () => {
try {
const response = await fetch('/getName')
const resp = await response.json();
console.log("Obj returned from server", resp)
} catch (error) {
console.log('Fetch error: ', error);
}
}
</script>
</head>
<body>
<button onclick="getName()">getName</button>
</body>
For a full working example (e.g. including a Flask app.py file and a Flask template) see:
https://github.com/lfernandez55/REST-auth/tree/stack-overflow-67606023
Answered By - Luke
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.