[英]Javascript - Async await and fetch - return the value, not the promise?
[英]await fetch in flask not getting required return
我正在尝试在 JS 中使用 await fetch 来使用我在 Flask 中创建的 function。 我的 JS 代码是:
let dictionary = await fetch("/getName");
let user_name = await dictionary.name;
我在 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)
为什么这不起作用? 具体到导致网站有 400 错误请求。
我从两个变量中删除了 await 功能,而是创建了错误:
“请求”object 没有属性“is_xhr”
我将 werkzeug 降级到 0.16.1,但什么也没有出现。 没有任何错误,但系统没有任何内容,也没有打印任何内容。 这是我的 JS 新代码。 (烧瓶保持不变)
let dictionary = fetch("/getName");
console.log("start");
console.log(dictionary);
let user_name = dictionary.name;
很可能您没有将 await 代码包装在已使用 async 声明的 function 中。 或者您错误地声明了异步 function。 这个例子有效:
您的 Flask 查看/路线:
@app.route('/getName')
def get_name():
print("in getName view....")
output = {"name": ""}
return jsonify(output)
您的客户端代码调用上述 /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>
有关完整的工作示例(例如,包括 Flask app.py 文件和 Flask 模板),请参阅:
https://github.com/lfernandez55/REST-auth/tree/stack-overflow-67606023
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.