【问题标题】:Simple fetch GET request in javascript to a flask server在 javascript 中简单地获取 GET 请求到烧瓶服务器
【发布时间】:2020-01-13 10:05:10
【问题描述】:

我正在尝试将一些 json 数据从烧瓶服务器显示到我的 html 页面,但我有一个 TypeError: NetworkError when attempting to fetch resource. 和一个 Promise { <state>: "rejected" }。

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

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

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]。

我做了最简单的代码,但它不起作用。

【问题讨论】:

  • 试试这个 stackoverflow.com/questions/57857647/… fetch 是一个可能有问题的新 api。我使用的代码绝对有效,应该至少返回一些东西。
  • 我肯定在这里用你的代码做错了我仍然有一个网络错误NetworkError: A network error occurred. 但没有更多的承诺。我也用 axios 测试过同样的问题

标签: javascript python api flask fetch


【解决方案1】:

感谢大家的好回答 :) 这是我的最终代码:

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

script.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)
    })
}

【讨论】:

    【解决方案2】:

    fetch() 返回一个promise,如果你想使用.json() 它返回另一个promise。您可以使用 .then() 来获取 json 响应。

    fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())  
      .then(json => console.log(json))
      

    但是您的烧瓶服务器中可能还有一个与 cors 相关的错误,请在返回之前尝试此操作:

    response.headers.add('Access-Control-Allow-Origin', '*')
    

    【讨论】:

      【解决方案3】:

      这可能是由同源策略引起的。浏览器不允许调用不同的来源,除非服务器设置了特殊的 HTTP 标头。 如果您从浏览器打开此 html 文件,则服务器的来源 localhost 与浏览器中的来源不匹配,这可能是文件路径。您可以通过将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)
      

      现在没有网络错误,但您的承诺尚未完成,因此您需要为其添加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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-24
        • 1970-01-01
        • 1970-01-01
        • 2014-07-23
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多