hakk

software development, devops, and other drivel
Tree lined path

Example of adding CORS headers Flask

An example of adding CORS headers to a Flask app without using Flask-CORS.

from flask import Flask, request, jsonify, make_response
from werkzeug.datastructures import Headers

app = Flask(__name__)

@app.route('/', methods=['OPTIONS', 'GET', 'POST'])
def index():
    # output all request headers to terminal
    print(request.headers)
    
    if request.method == 'POST':
        # handle json post data here...
        print(request.get_json())

    headers = Headers()
    headers.add('Access-Control-Allow-Origin', '*')
    headers.add('Access-Control-Allow-Methods', 'OPTIONS', 'GET', 'POST')
    headers.add('Access-Control-Allow-Headers', 'Content-Type')
    headers.add('Access-Control-Max-Age', '300')
    
    resp = make_response(
                jsonify(
                    {'msg':'nailed it!'}
                )
            )
    
    resp.headers = headers
    return resp

if __name__ == '__main__':
    app.run(debug=True)