Solve Cross Origin Resource Sharing with Flask

后端 未结 9 725
面向向阳花
面向向阳花 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: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"}
    

提交回复
热议问题