javascript - 即使在服务器上成功,错误回调也总是触发
问题描述
我正在使用 Python 烧瓶和 JavaScript 学习 REST API。
我已经成功创建了 API,但是每当我尝试使用 Ajax 或 JavaScript 调用它时它都会失败,但在烧瓶服务器上它会显示 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
但在烧瓶后端成功:
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"
}
]
}
解决方案
后端成功发送 JSON 响应,但由于访问控制来源,获取承诺失败。通常,如果您使用flask jinja 提供HTML 代码,那么您将不会遇到问题。发生这种情况是因为 HTML 以不同的方式提供服务。
请在下面添加此代码以检查访问控制是否是真正的问题。
response = jsonify({'tasks': tasks})
response.headers.add("Access-Control-Allow-Origin", "*")
return response
烧瓶生态系统中有一个 corps 包,您可以使用它来轻松解决这些与 cors 相关的问题。烧瓶-cors
推荐阅读
- powerbi - 如何在主表中添加计算列,该列将从 dax 中的另一个表计算总和
- java - 将“.wav”文件读入java android作为“.tflite”模型的输入文件
- c++ - 在 C++11 上下文中使用 std::optional
- java - 在 macOSX 中的 Selenium 中的特定文件夹中下载文件
- html - 将 TextArea 绑定到字符串数组 - Angular 7
- javascript - 如何标记所选项目?
- postgresql - EntityFrameworkCore 将 ToTable 用于非默认实体名称不会在 PostgresSQL 中创建表
- reactjs - 反应自定义组件 - 无法根据道具设置状态
- omnet++ - 如何将车辆编程为 sdn 控制器?
- python - 如何在我的烧瓶应用程序的网页上显示来自 s3 的图像而不保存它?