Javascript - No 'Access-Control-Allow-Origin' header is present on the requested resource

后端 未结 7 1786
天命终不由人
天命终不由人 2020-11-27 17:25

I need to send data through XmlHttpRequest from JavaScript to Python server. Because I\'m using localhost, I need to use CORS. I\'m using the Flask framework an

7条回答
  •  借酒劲吻你
    2020-11-27 18:03

    When using python 2.7

    app = Flask(__name__)
    api = Api(app)
    
    @app.after_request
    def after_request(response):
      response.headers.add('Access-Control-Allow-Origin', '*')
      response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
      response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
      return response
    
    
    if __name__ == '__main__':
        app.run()
    

    When running on python3 or ahead, install flask-cors using the command pip install flask-cors The add the following:

    from flask_cors import CORS
    app = Flask(__name__)
    CORS(app)
    

提交回复
热议问题