在JavaScript中简单地获取GET请求到Flask服务器 [英] Simple fetch GET request in javascript to a flask server

查看:41
本文介绍了在JavaScript中简单地获取GET请求到Flask服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从烧瓶服务器向html页面显示一些json数据,但是尝试获取资源时出现 TypeError:NetworkError.带有 Promise {< state>;:"rejected"} .

I'm trying to display some json data from a flask server to my html page but I have a TypeError: NetworkError when attempting to fetch resource. with a Promise { <state>: "rejected" }.

server.py

server.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)

script.js

script.js

function getHello() {
    const url = 'http://localhost:8989/hello'
    const response = fetch(url)
    console.log(response);
    document.getElementById("demo").innerHTML = response;
}

index.html

index.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] .

I also have a [object Promise] in the label section when I click on the button.

我做了最简单的代码,但是没用.

I did the simplest code possible but it doesn't work.

推荐答案

这可能是由于同源策略"引起的.除非服务器设置特殊的HTTP标头,否则浏览器不允许调用其他来源.如果您是从浏览器中打开此html文件,则本地服务器的来源与浏览器中的来源(可能是文件路径)不匹配.您可以通过在响应中添加 Access-Control-Allow-Origin 标头来使其工作,如下所示:

This could be caused by Same-Origin Policy. Browser does not allow making calls to different origin unless server sets special HTTP header. If you are opening this html file from your browser, the origin of server which is localhost does not match with the origin in your browser which is probably a file path. You can make it work by adding Access-Control-Allow-Origin header to the response as follows:

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)

现在没有网络错误,但是您的承诺尚未完成,因此您需要为其添加然后.

Now there is no network error but your promise is pending so you need to add then for it.

或者,您也可以通过Flask服务器提供index.html文件,以使原点匹配.

Alternatively you can serve index.html file by your Flask server so that origins match.

您可以在此处了解有关CORS和SOP的更多信息:

You can read more about CORS and SOP here:

https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS

这篇关于在JavaScript中简单地获取GET请求到Flask服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆