Solve Cross Origin Resource Sharing with Flask

后端 未结 9 685
面向向阳花
面向向阳花 2020-11-28 03:59

For the following ajax post request for Flask (how can I use data posted from ajax in flask?):

$.ajax({
    url: \"http://127.0.0.1         


        
相关标签:
9条回答
  • 2020-11-28 04:04

    I struggled a lot with something similar. Try the following:

    1. Use some sort of browser plugin which can display the HTML headers.
    2. Enter the URL to your service, and view the returned header values.
    3. Make sure Access-Control-Allow-Origin is set to one and only one domain, which should be the request origin. Do not set Access-Control-Allow-Origin to *.

    If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.

    CORS That Works In IE, Firefox, Chrome And Safari

    0 讨论(0)
  • 2020-11-28 04:05

    You can get the results with a simple:

    @app.route('your route', methods=['GET'])
    def yourMethod(params):
        response = flask.jsonify({'some': 'data'})
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    
    0 讨论(0)
  • 2020-11-28 04:13

    Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.

    Install flask-cors

    pip install -U flask-cors
    

    then after app initialization, initialize flask-cors with default arguments:

    from flask import Flask
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    
    @app.route("/")
    def helloWorld():
       return "Hello, cross-origin-world!"
    
    0 讨论(0)
  • 2020-11-28 04:14

    It worked like a champ, after bit modification to your code

    # initialization
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
    app.config['CORS_HEADERS'] = 'Content-Type'
    
    cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})
    
    @app.route('/foo', methods=['POST'])
    @cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
    def foo():
        return request.json['inputVar']
    
    if __name__ == '__main__':
       app.run()
    

    I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain

    0 讨论(0)
  • 2020-11-28 04:20

    Might as well make this an answer. I had the same issue today and it was more of a non-issue than expected. After adding the CORS functionality, you must restart your Flask server (ctrl + c -> python manage.py runserver, or whichever method you use)) in order for the change to take effect, even if the code is correct. Otherwise the CORS will not work in the active instance.

    Here's how it looks like for me and it works (Python 3.6.1, Flask 0.12):

    factory.py:

    from flask import Flask
    from flask_cors import CORS  # This is the magic
    
    
    def create_app(register_stuffs=True):
        """Configure the app and views"""
        app = Flask(__name__)
        CORS(app)  # This makes the CORS feature cover all routes in the app
    
        if register_stuffs:
            register_views(app)
        return app
    
    
    def register_views(app):
        """Setup the base routes for various features."""
        from backend.apps.api.views import ApiView
        ApiView.register(app, route_base="/api/v1.0/")
    

    views.py:

    from flask import jsonify
    from flask_classy import FlaskView, route
    
    
    class ApiView(FlaskView):
        @route("/", methods=["GET"])
        def index(self):
            return "API v1.0"
    
        @route("/stuff", methods=["GET", "POST"])
        def news(self):
            return jsonify({
                "stuff": "Here be stuff"
            })
    

    In my React app console.log:

    Sending request:
    GET /stuff
    With parameters:
    null
    bundle.js:17316 Received data from Api:
    {"stuff": "Here be stuff"}
    
    0 讨论(0)
  • 2020-11-28 04:22

    Note: The placement of cross_origin should be right and dependencies are installed. On the client side, ensure to specify kind of data server is consuming. For example application/json or text/html

    For me the code written below did magic

    from flask import Flask,request,jsonify
    from flask_cors import CORS,cross_origin
    app=Flask(__name__)
    CORS(app, support_credentials=True)
    @app.route('/api/test', methods=['POST', 'GET','OPTIONS'])
    @cross_origin(supports_credentials=True)
    def index():
        if(request.method=='POST'):
         some_json=request.get_json()
         return jsonify({"key":some_json})
        else:
            return jsonify({"GET":"GET"})
    
    
    if __name__=="__main__":
        app.run(host='0.0.0.0', port=5000)
    
    0 讨论(0)
提交回复
热议问题