我正在尝试将一些 json 数据从 Flask 服务器显示到我的 html 页面,但我有一个TypeError: NetworkError when attempting to fetch resource.
with a Promise { <state>: "rejected" }
.
服务器.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello():
jsonResp = {'jack': 4098, 'sape': 4139}
print(jsonify(jsonResp))
return jsonify(jsonResp)
if __name__ == '__main__':
app.run(host='localhost', port=8989)
脚本.js
function getHello() {
const url = 'http://localhost:8989/hello'
const response = fetch(url)
console.log(response);
document.getElementById("demo").innerHTML = response;
}
索引.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button onclick="getHello()">click</button>
<label id="demo"></label>
<script src="script.js"></script>
</body>
</html>
我也有一个[object Promise]
当我单击按钮时在标签部分中。
我做了最简单的代码,但它不起作用。
谢谢大家的好回答:)
这是我的最终代码:
服务器.py
from flask import Flask, request, jsonify, after_this_request
app = Flask(__name__)
@app.route('/hello', methods=['GET'])
def hello():
@after_this_request
def add_header(response):
response.headers.add('Access-Control-Allow-Origin', '*')
return response
jsonResp = {'jack': 4098, 'sape': 4139}
print(jsonResp)
return jsonify(jsonResp)
if __name__ == '__main__':
app.run(host='localhost', port=8989)
脚本.js
function getHello() {
const url = 'http://localhost:8989/hello'
fetch(url)
.then(response => response.json())
.then(json => {
console.log(json);
document.getElementById("demo").innerHTML = JSON.stringify(json)
})
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)