我有一個后端 cython flask 應用程式,它有一個帶有路由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時,端點作業正常。有人可以幫我嗎?
uj5u.com熱心網友回復:
mode: no-cors在您的 Flask 端點中,此處使用不當,將導致回應type: "opaque"主體不可讀。在這里解釋。
瀏覽器不允許跨源請求作業,除非服務器明確允許它們。
解決此問題的一種方法是使用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://www.uj5u.com/caozuo/536275.html
上一篇:從FLASK請求函式
