Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How do I enable CORS? #421

Open
Jerakin opened this issue Mar 25, 2022 · 4 comments
Open

How do I enable CORS? #421

Jerakin opened this issue Mar 25, 2022 · 4 comments
Labels
question Further information is requested

Comments

@Jerakin
Copy link

Jerakin commented Mar 25, 2022

Summary: Trying to add CORS to my flask-restx app but failing. Is my setup correct? Can someone see if there is something wrong with my general setup or if flask-restx simply doesn't work with the kind of setup I am trying to accomplish?

I have made a issue on https://github.com/corydolphin/flask-cors (#308) too, but now I am thinking that it's probably on flask-restx side on things maybe.

In the console that is running flask I don't get any relevant logs and the website is saying Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/api/v1/test. (Reason: CORS request did not succeed). Status code: (null). I don't even get any indication in the logs that the server received an "OPTIONS" request.

I would greatly appreciate it if someone could just run my repro case below so that I at least know that it isn't just my machine.

from flask import Flask
from flask_cors import CORS
from flask_restx import Namespace, Resource, Api
from flask import jsonify, make_response
from flask import Blueprint, render_template_string
import logging

logging.basicConfig()
LOGGER = logging.getLogger("reprod-case")
LOGGER.setLevel(logging.DEBUG)
LOGGER.info("Created LOGGER")
logging.getLogger('flask_cors').level = logging.DEBUG


# Create the restx namespace with a specified path
ns = Namespace(name='api_v1', path="/api/v1")


@ns.route('/test')
class Deck(Resource):
    def get(self):
        print("get")
        return make_response(jsonify({"message": "You did a Get!"}), 200)

    def put(self):
        print("Put")
        return None, 201


html_page = """
<html lang="en">
<body>
<button type="submit" name="myButton" value="Value">Click Me</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $('button').on('click',function(e){
        const vote_value = e.currentTarget.attributes.value.value;
        console.log()
        $.ajax({
            type: 'GET',
            crossDomain: true,
            withCredentials: true,
            url: 'http://127.0.0.1/api/v1/test',
            contentType: 'application/json'
        })
    });
});
</script>
</body>
</html>
"""


# Blueprint for the webpage and add a route
bp = Blueprint("/", __name__)


@bp.route('/')
def home_route():
    return render_template_string(html_page)


# Setup the app, Cors, add the namespace and blueprint
def create_app():
    app = Flask(__name__)
    # CORS(app, resources={r"/api/*": {"origins": "*"}},
    CORS(app,
         resources={r"/api/*": {"origins": ['http://192.168.50.16:5000', 'http://localhost:5000']}},
         supports_credentials=True
         )

    api = Api(doc="/api/", title="Endpoints")
    api.add_namespace(ns,  path="/api/v1")
    app.register_blueprint(bp)
    api.init_app(app)
    return app


if __name__ == "__main__":
    app_ = create_app()
    app_.run(debug=True)

Running it with FLASK_ENV=development and simply flask run .

@Jerakin Jerakin added the question Further information is requested label Mar 25, 2022
@MMichels
Copy link

MMichels commented Apr 11, 2022

You need to add a "After request" function on your app definitiion, like:

app = Flask(name)
@app.after_request
def enable_cors(response):
response.headers.add("Access-Control-Allow-Headers", "authorization,content-type")
response.headers.add("Access-Control-Allow-Methods", "DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT")
response.headers.add("Access-Control-Allow-Origin", "*")
return response

@Jerakin
Copy link
Author

Jerakin commented Apr 12, 2022

Hi! Did you try to add this in the example I provided? I tried adding it there and it didn't do anything. I tried to add it under if __name__ == "__main__", tried just after it was initialized in create_app(). Also tried to do add it directly without the decorator like so app.after_request(enable_cors). Nothing worked. :(

@lvhao54
Copy link

lvhao54 commented Jun 29, 2022

@Jerakin Hi! Have you found a solution?

@Jerakin
Copy link
Author

Jerakin commented Sep 5, 2022

Paused working on this part of the website for a while, until a few days ago and am still unable to solve it even with a fresh mindset. Adding to our plight is that this project now looks like it is no longer maintained, in the future I will have to look into migrating away from restx and would recommend others to do the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

3 participants