[英]CORS header 'Access-Control-Allow-Origin' missing despite header begin there
I'm making an api in flask-restful, and I'm trying to make a request, but when I try I get the error:我正在烧瓶中制作 api,我正在尝试提出请求,但是当我尝试时出现错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:5000/events/. (Reason: CORS header 'Access-Control-Allow-Origin' missing)
My code is:我的代码是:
class Event(Resource):
def get(self, id=0):
if id == 0:
return random.choice(events), 200
for event in events:
if(event["id"] == id):
return event, 200, {'Access-Control-Allow-Origin': '*'}
return "Event not found", 404
I have added the header, but I stil get the error.我已经添加了 header,但我仍然收到错误。 Does anyone know what the problem is?
有谁知道问题是什么? Also, if anyone needs it, the full code is here:
另外,如果有人需要,完整的代码在这里:
from flask import Flask
from flask_restful import Api, Resource, reqparse
import random
app = Flask(__name__)
api = Api(app)
events = [
{
"id": 0,
"starter": "a",
"dungeon": "test a",
"info": "A test event for the web app and api"
},
{
"id": 1,
"starter": "b",
"dungeon": "test b",
"info": "A test event for the web app and api 2"
}
]
class Event(Resource):
def get(self, id=0):
if id == 0:
return random.choice(events), 200
for event in events:
if(event["id"] == id):
return event, 200, {'Access-Control-Allow-Origin': 'file:///C:/Python/website%20test/index.html'}
return "Event not found", 404
api.add_resource(Event, "/events", "/events/", "/events/<int:id>")
if __name__ == '__main__':
app.run(debug=True)
Edit: Here is how I am making the request:编辑:这是我提出请求的方式:
let request = new XMLHttpRequest();
request.open("GET", "http://127.0.0.1:5000/events/");
request.send();
request.onload = () => {
if (request.status == 200) {
console.log(JSON.parse(request.response));
} else {
console.log('API offline');
}
}
install flask-CORS package.安装烧瓶-CORS package。
pip install -U flask-cors
and apply the following changes.并应用以下更改。 On your current code.
在您当前的代码上。
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.