Search code examples
pythonflask-restful

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:

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. 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');
    }
}

Solution

  • install flask-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!"