Skip to content
hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets

Ajax

  • Example of adding CORS headers Flask 2022-11-04

    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)
    

Recent posts
  • How to Update a File's Creation Time in PowerShell
  • How to Run PowerShell Code Only During Certain Times
  • PeopleSoft App Server Freeze Troubleshooting Checklist
  • Build Vim With Python3 Support
  • Understanding the ss Command: A Modern Alternative to netstat
© 2026 hakk
  • Home
  • Blog
  • Docs
  • DSA
  • Snippets