Python Flask Cors Issue Python Flask Cors Issue flask flask

Python Flask Cors Issue


After I tried others suggestions and answers. Here's what I use, which works.

Steps:

  1. pip install flask flask-cors

  2. Copy and paste this in app.py file

Code

from flask import Flask, jsonifyfrom flask_cors import CORS, cross_originapp = Flask(__name__)CORS(app, support_credentials=True)@app.route("/login")@cross_origin(supports_credentials=True)def login():  return jsonify({'success': 'ok'})if __name__ == "__main__":  app.run(host='0.0.0.0', port=8000, debug=True)
  1. python app.py

Note: be sure in your client's ajax configuration has the following:

$.ajaxSetup({    type: "POST",    data: {},    dataType: 'json',    xhrFields: {       withCredentials: true    },    crossDomain: true,    contentType: 'application/json; charset=utf-8'});

If one wonders, support_credentials=True just means it sends cookies along the payload back and forth.


Flask has the flask-cors module.Following is the code snippet as well as the procedure.

  1. pip install -U flask-cors

  2. Add this lines in your flask application:

    from flask import Flaskfrom flask_cors import CORS, cross_originapp = Flask(__name__)CORS(app)@app.route("/")def helloWorld():    return "Hello world"

See more by clicking on this link


Here is how to get your hand dirty by handling the CORS detail all by yourself:

handle_result = {'result': True, 'msg': 'success'}try:    # origin, where does this request come from, like www.amazon.com    origin = flask.request.environ['HTTP_ORIGIN']except KeyError:    origin = None# only accept CORS request from amazon.comif origin and origin.find('.amazon.com') > -1:    resp = flask.make_response(str(handle_result))    resp.headers['Content-Type'] = 'application/json'    h = resp.headers    # prepare headers for CORS authentication    h['Access-Control-Allow-Origin'] = origin    h['Access-Control-Allow-Methods'] = 'GET'    h['Access-Control-Allow-Headers'] = 'X-Requested-With'    resp.headers = h    return respreturn flask.abort(403)