Flask Access-Control-Allow-Origin for multiple URLs
This is typical scenario when working locally with multiple instances of the same frontend project accessing together to a local Flask server, and when the wildcard "*" is not allowed because you are allowing credentials (i.e. using a JWT authentication).
My approach - in development - is to use the after_request decorator and Flask's request context.
Create a domain whitelist:
white = ['http://localhost:8080','http://localhost:9000']
Now use the after_request
decorator to intercept all incoming requests, check if the referrer is in your whitelist and, if it is, inject the response.headers
to allow access to the origin. For example:
from flask import request@app.after_requestdef add_cors_headers(response): r = request.referrer[:-1] if r in white: response.headers.add('Access-Control-Allow-Origin', r) response.headers.add('Access-Control-Allow-Credentials', 'true') response.headers.add('Access-Control-Allow-Headers', 'Content-Type') response.headers.add('Access-Control-Allow-Headers', 'Cache-Control') response.headers.add('Access-Control-Allow-Headers', 'X-Requested-With') response.headers.add('Access-Control-Allow-Headers', 'Authorization') response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE') return response
Simple example,try it!
I hope it will help you.You need to edit white_origin for 'Access-Control-Allow-Origin'.
app_name.py (Python file of Flask )
from flask import request@app.after_requestdef after_request(response): white_origin= ['http://www.dom.com:8000','http://localhost'] if request.headers['Origin'] in white_origin: response.headers['Access-Control-Allow-Origin'] = request.headers['Origin'] response.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE' response.headers['Access-Control-Allow-Headers'] = 'Content-Type,Authorization' return response