即使在服务器上成功,错误回调也总是会触发

时间:2021-05-01 19:08:28

标签: javascript ajax api rest flask

我正在使用 Python Flask 和 JavaScript 学习 REST API。

我已经成功创建了 API,但是每当我尝试使用 Ajax 或 JavaScript 调用它时,它都会失败,但在 Flask 服务器上它会显示 200 响应。

我的烧瓶代码:

from flask import Flask, jsonify

app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web', 
        'done': False
    }
]

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': tasks})

if __name__ == '__main__':
    app.run(debug=True)

HTML 代码:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Api Learn</title>
    <script src="js/jQuery.js" type="text/javascript" charset="utf-8"></script>
    <link rel="stylesheet" href="bulma/bulma.css" type="text/css" media="all" />
</head>
<body>
    <section class="section">
        <button id="fetch" class="button is-link is-large">Click</button>
    </section>
    <script type="text/javascript" src="js/main.js"></script>
</body>
</html>

JavaScript 代码:

const baseUrl = "http://127.0.0.1:5000/todo/api/v1.0/tasks";


$("document").ready(function() {
    $("#fetch").click(function() {
        fetch(baseUrl)
        .then(function(data) {
            console.log(data)
        })
        .catch(function(error) {
            console.log(error)
        })

    })
});

控制台上的错误消息:

stack:TypeError: Failed to fetch
message:Failed to fetch

但在 Flask 后端成功:

127.0.0.1 - - [01/May/2021 20:03:51] "GET /todo/api/v1.0/tasks HTTP/1.1" 200 -

每当我用 curl 调用它时,它总是成功的:

$ curl -i "http://localhost:5000/todo/api/v1.0/tasks"

卷曲响应:

HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 317
Server: Werkzeug/1.0.1 Python/3.9.4
Date: Sat, 01 May 2021 19:06:23 GMT

{
  "tasks": [                                    {
      "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
      "done": false,
      "id": 1,
      "title": "Buy groceries"
    },                                          {
      "description": "Need to find a good Python tutorial on the web",
      "done": false,
      "id": 2,
      "title": "Learn Python"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

后端成功发送 JSON 响应,但由于访问控制源,获取承诺失败。通常,如果您使用flask jinja 提供HTML 代码,那么您将不会遇到问题。这是因为 HTML 的服务方式不同。

请在下面添加此代码以检查访问控制是否是真正的问题。

response =  jsonify({'tasks': tasks})
response.headers.add("Access-Control-Allow-Origin", "*")
return response

flask 生态系统中有一个 corps 包,您可以使用它轻松解决那些与 cors 相关的问题。 flask-cors