我有一个后端cython烧瓶应用程序,它有一个带有路由http://127.0.0.1:8000/items的GET端点。我的第二个应用程序是一个在http://127.0.0.1:5000托管的html网站。我正试图从我的网站发送一个请求到这个端点。
烧瓶应用程序:
@app.route('/items', methods=["GET"])
def getPrices():
.......
# "stuff" is a list with json objects [{"x": "y"}, {"x": "z"}, ....]
return {
"items": stuff
}
我试着把它拿来:
let response = await fetch(
'http://127.0.0.1:8000/items',
{
method: 'GET',
mode: 'no-cors' // if i don't do this im getting fetch blocked by cors error
});
console.log(response);
不过,这是我得到的回应
Response {type: 'opaque', url: '', redirected: false, status: 0, ok: false, …}
body: null
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
[[Prototype]]: Response
当我在浏览器中访问http://127.0.0.1:8000/items时,端点可以正常工作。有人能帮我吗?
发布于 2022-11-15 18:53:57
您的烧瓶端点中的mode: no-cors
在这里被错误地使用,并将导致type: "opaque"
的响应,这些响应具有不可读的主体。Explained here。
浏览器不允许跨源请求工作,除非服务器显式允许它们。
解决这一问题的一种方法是使用flask-cors
(可以通过pip安装),例如:
from flask import Flask
from flask-cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
# or, if you want some specific (or any) route to allow
# any cross-origin request
cors = CORS(app, resources={r"/some-route/*": {"origins": "*"}})
@app.route("/")
# this decorator is only necessary if the origin wasn't set earlier
@cross_origin()
def my_api():
return "This request works cross-origin!"
https://stackoverflow.com/questions/74450757
复制相似问题