The*_*key 9 javascript python flask fetch-api
我正在尝试将一些 json 数据从 Flask 服务器显示到我的 html 页面,但我有一个TypeError: NetworkError when attempting to fetch resource.带有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)
Run Code Online (Sandbox Code Playgroud)
脚本.js
function getHello() {
const url = 'http://localhost:8989/hello'
const response = fetch(url)
console.log(response);
document.getElementById("demo").innerHTML = response;
}
Run Code Online (Sandbox Code Playgroud)
索引.html
function getHello() {
const url = 'http://localhost:8989/hello'
const response = fetch(url)
console.log(response);
document.getElementById("demo").innerHTML = response;
}
Run Code Online (Sandbox Code Playgroud)
[object Promise]当我单击按钮时,标签部分中也会出现。
我做了最简单的代码,但它不起作用。
The*_*key 14
感谢大家的良好回答:)这是我的最终代码:
服务器.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)
Run Code Online (Sandbox Code Playgroud)
脚本.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)
})
}
Run Code Online (Sandbox Code Playgroud)
这可能是由同源策略引起的。除非服务器设置特殊的 HTTP 标头,否则浏览器不允许调用不同的源。如果您从浏览器打开此 html 文件,则服务器的源(本地主机)与浏览器中的源(可能是文件路径)不匹配。Access-Control-Allow-Origin您可以通过向响应添加标头来使其工作,如下所示:
from flask import after_this_request
@app.route('/hello', methods=['GET'])
def hello():
@after_this_request
def add_header(response):
response.headers['Access-Control-Allow-Origin'] = '*'
return response
jsonResp = {'jack': 4098, 'sape': 4139}
print(jsonify(jsonResp))
return jsonify(jsonResp)
Run Code Online (Sandbox Code Playgroud)
现在没有网络错误,但您的承诺尚未完成,因此您需要then为其添加。
或者,您可以通过 Flask 服务器提供 index.html 文件,以便源匹配。
您可以在此处阅读有关 CORS 和 SOP 的更多信息:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
| 归档时间: |
|
| 查看次数: |
21100 次 |
| 最近记录: |