简体   繁体   中英

CORS errors with Flask and gevent

I have an API running, using Flask, Flask-SQLAlchemy, and Flask-Restless, and am trying to make POST/PUT/DELETE requests from javascript (backbone.js, to be precise). However, I keep running into CORS errors - everything except GET returns an HTTP OPTIONS 501 Not Implemented Error in the browser.

Initially, I tried adding the least restrictive CORS headers possible to all responses:

@app.after_request
def after(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Methods',
                         'POST, GET, PUT, PATCH, DELETE, OPTIONS')
    response.headers.add('Access-Control-Allow-Headers',
                         'Content-Type, X-Requested-With')
    response.headers.add('Access-Control-Max-Age', '1728000')

    return response

CORS seemed to fail when the request's Content-Type header was set to application/json (as required by the API), so a quick hack was made to get things working:

@app.before_request
def before():
    request.environ['CONTENT_TYPE'] = 'application/json'

However, everything except POST still fails. Also, gevent's logging is turned on, but no OPTIONS requests are ever logged (which I believe is the CORS preflight stuff), even when the browser shows them failing with a 501.

Do I need to change something in gevent or Flask to get CORS working?

Edit: Running the API using the built-in Flask server works, so gevent is the problem here, but I can't seem to find much in the way of docs...

有一个用于HTTP访问控制的烧瓶片段装饰器 ,您可以使用@crossdomain(origin ='*')装饰器。

Simplest way is to use flask-cors plugin

Install using pip

pip install -U flask-cors

Sample Code

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route("/api/v1/users")
def list_users():
  return "user example"

For documentationh head over here flask-cors documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM