[英]await fetch in flask not getting required return
I'm trying to use await fetch in JS to use a function that I created in Flask.我正在尝试在 JS 中使用 await fetch 来使用我在 Flask 中创建的 function。 My code for the JS is:
我的 JS 代码是:
let dictionary = await fetch("/getName");
let user_name = await dictionary.name;
and my code in flask is:我在 flask 中的代码是:
@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.
具体到导致网站有 400 错误请求。
I removed the await feature from both of the variables, and instead it creates the error:我从两个变量中删除了 await 功能,而是创建了错误:
'Request' object has no attribute 'is_xhr'
“请求”object 没有属性“is_xhr”
I downgraded werkzeug to 0.16.1, and no nothing just shows up.我将 werkzeug 降级到 0.16.1,但什么也没有出现。 There aren't any errors, but nothing comes and nothing gets printed by the system.
没有任何错误,但系统没有任何内容,也没有打印任何内容。 Here is my new code for JS.
这是我的 JS 新代码。 (Flask stays the same)
(烧瓶保持不变)
let dictionary = fetch("/getName");
console.log("start");
console.log(dictionary);
let user_name = dictionary.name;
Most likely you haven't wrapped the await code inside a function that has been declared with async.很可能您没有将 await 代码包装在已使用 async 声明的 function 中。 Or you have declared the async function incorrectly.
或者您错误地声明了异步 function。 This example works:
这个例子有效:
Your Flask view/route:您的 Flask 查看/路线:
@app.route('/getName')
def get_name():
print("in getName view....")
output = {"name": ""}
return jsonify(output)
Your client side code calling the above /getName route:您的客户端代码调用上述 /getName 路由:
<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 (eg including a Flask app.py file and a Flask template) see:有关完整的工作示例(例如,包括 Flask app.py 文件和 Flask 模板),请参阅:
https://github.com/lfernandez55/REST-auth/tree/stack-overflow-67606023 https://github.com/lfernandez55/REST-auth/tree/stack-overflow-67606023
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.