Flask serving static folder with CORS - python

In my frontend app I'm trying to access a file I'm serving in a static folder but I'm getting an issue with CORS. The issue I'm seeing is
Access to XMLHttpRequest at 'http://127.0.0.1:5000/static_folder/apple.xml' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My backend Flask app has the following set
app = Flask(__name__, static_url_path='/static_folder', static_folder="static_folder")
It seems that I need to add the 'Access-Control-Allow-Origin' header to my responses when returning the files. Does Flask have a global way to set this?
I've tried using flask_cors but haven't been successful with
from flask_cors import CORS, cross_origin
app = Flask(__name__, static_url_path='/static_folder', static_folder="static_folder")
CORS(app)
I was able to get something similar working with the SimpleHTTPRequestHandler by setting the CORS headers as
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
SimpleHTTPRequestHandler.end_headers(self)
But I'd like to use flask to accomplish this rather than starting a simple http server.

after cors(app) add these lines:
#app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE, OPTIONS')
return response

Also, if using the flask-cors package, you should be able to blanket your static requests:
from flask import Flask
from flask_cors import CORS
# Initialize
app = Flask(__name__)
cors = CORS(app, resources={r"/static/*": {"origins": "*"}})
Good luck!

Related

Flask cors not allowing request from my react web app (even with cors enabled)

im having many issues with my backend flask API with CORS. I have done everything which flask documentation and stackover flow says, but I still get this error. Even with cors enabled. Anyone know what is wrong?
Even adding the flask decorator for cross_origin doesn't resolve the issues
from flask import Flask, render_template, request, session, redirect, jsonify, abort
from flask_cors import CORS
import pymongo
from config import get_env_var
from utils import get_token, get_user_information
app = Flask(__name__)
CORS(app)
#app.route("/oauth/discord", methods=["POST"])
def oauth():
Access to XMLHttpRequest at 'http://127.0.0.1:5000/oauth/callback' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Javascript / Flask - No 'Access-Control-Allow-Origin' header is present on the requested resource

I have a FlaskAPI back-end and a Vue front-end and I am trying to send responses between the two. I am having an issue with the implementation of FlaskCors. This module should handle 'OPTIONS' as well from what I can tell, however I am having issues still. Any help would be appreciated. The documentation does not say to utilize the '#cross-origin' decorator if I choose to allow everything.
Javascript error:
Access to XMLHttpRequest at 'http://localhost:5000/login' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource.
Flask Runner
#! /usr/bin/python3.6
from caffeine import create_app
import os
app = create_app()
# app.secret_key = os.environ.get("SECRET_KEY")
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=5000)
init.py
import os
from pathlib import Path
from flask_api import FlaskAPI
from flask_cors import CORS
from caffeine.config import Config
def create_app():
"""Instantiates and initialize the Flask application"""
app = FlaskAPI(__name__)
app.config.from_object(Config)
CORS(app)
from caffeine.routes.bp_auth import auth
app.register_blueprint(auth)
return app
Flask Config:
class Config:
"""Base configuration."""
API_VERSION = "1.0.0"
SECRET_KEY = os.environ.get("SECRET_KEY")
CORS_HEADERS = "Access-Control-Allow-Origin"
Flask Auth Blueprint:
#auth.route("/login", methods=["GET", "POST", "OPTIONS"])
def login():
"""
present the 'login-page' for entering LDAP credentials to be validated and added to the database
if user is already authenticated, they will be routed to the home route (routes.py)
:return: user login-in UI view
"""
if request.method == "POST":
user_sso = request.data["sso"].strip()
access_token = encode_access_token(user_sso)
response = jsonify(
status="success",
message="successfully logged in",
access_token=access_token,
token_type="bearer",
expires_in=get_token_expire_time(),
)
response.status_code = HTTPStatus.CREATED
response.headers["Cache-Control"] = "no-store"
response.headers["Pragma"] = "no-cache"
return response
i've had a similar problem with react, this is how i could solve it on my app:
class config:
CORS_ALLOW_CREDENTIALS = True
init.py
...
from flask_cors import CORS
cors = CORS()
def create_app():
...
cors.init_app(app=app, supports_credentials=True)
...

How to allow Cross Origin Request with Flask CORS correctly?

I'm trying to allow Same Origin request to my Flask app:
this is in my __init__.py file:
# ... other imports ...
from flask_cors import CORS
cors = CORS()
def create_app(script_info=None):
app = Flask(__name__)
app_settings = os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
from project.api.flakes import flakes_blueprint
app.register_blueprint(flakes_blueprint)
cors.init_app(flakes_blueprint, resources={r"/flakes": {"origins": "*"}})
return app
According to docs this should be sufficient to get it working but I get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5001/flakes. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
How can I get it working ? I would've thought {"origins": "*"} covers everything.
I've not seen an example like you have provided using cors_init_app(), so cannot comment on why it doesn't work.
However, here is an example of I've used previously that works:
app = Flask(__name__)
CORS(app, resources={r'/*': {'origins': '*'}})
app.config['CORS_HEADERS'] = 'Content-Type'
app.register_blueprint(my_blueprint_module.bp)

Problem with CORS, not allowing communication

CORS not allowing communication. Headers not found
Using Python 3.7 and the webapp is hosted in pythonanywhere.com
This is how I'm calling CORS in my code:
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route('/', methods=['GET', 'POST'])
....
....
The Error I'm getting is this:
"Access to XMLHttpRequest at 'https‍://user.pythonanywhere.com/' from origin 'http‍://www.example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."
Please assist. Don't know what I am missing or where. It says header is missing. How do I add it to allow communication? Where do I add it?
Let the CORS for all the resources in the app.
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})
Also, please make sure you don't have any other CORS browser extension that is doing the hampering the module you have in the program.

flask-cors not sending preflight CORS request

I want to allow only localhost as access-control-allow-origin in my Flask app. I tried searching for this issue at other places with no solution. My code is very simple and straightforward as follows :
from flask import Flask
from routes.routes import *
from flask_cors import CORS
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "http://localhost:3000"}})
app.wsgi_app = PrefixMiddleware(app.wsgi_app, prefix='/drax')
app.add_url_rule('/template/<actionId>/<actionName>', None, templateActions, methods=['GET'])
The above should ONLY allow any request from localhost:3000 and not from anywhere else, like localhost:8080. But even when I make the request from port 8080 (another web app), it allows the request.
Looks like you need to specify a valid http origin in your request as under:
CORS(
app,
supports_credentials=True,
resources={
r"/*": {
"origins": [
"http://localhost:3000",
""http://localhost"
"http://127.0.0.1:3000",
"http://127.0.0.1,
]
}
},
)
I do not think http://local is a valid origin

Categories

Resources