I have an app with fastapi (v0.88) backend that connect to an API built using flask (v2.2). The frontend is build using ReactJS (v18.2).
ReactJS ---------> FastAPI --------------> Flask
(frontend) (backend) (API Server)
Frontend: local Backend: Backend server (not local) API: API Server (not local)
The API (using Flask) is already deployed on the server with CORS enabled. For simplicity, the CORS is enabled the following way:
from flask_cors import CORS
def initialize_app(env=None):
app = Flask(__name__,
instance_path=dirname(realpath(__file__)),
instance_relative_config=True)
app.config.from_object(config_by_name[env])
app.config['SWAGGER_UI_DOC_EXPANSION'] = 'list'
CORS(app)
with app.app_context():
register_extensions(app)
register_blueprints(app)
return app
In the fastapi, I've done the following:
from fastapi.middleware.cors import CORSMiddleware
# Set all CORS enabled origins
if cnf.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
# allow_origins=[str(origin)
# for origin in cnf.BACKEND_CORS_ORIGINS],
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
When I make the call from the front end, I simply do the following. This makes the call to the backed (FastAPI).
var headers: Headers = {
'Content-Type': 'application/json; charset=utf-8'
}
export const GET = (url:string) => {
return axios.get(`${url}`, { headers });
};
export const POST = (url:string, data:any) => {
return axios.post(`${url}`, {
headers,
data
});
};
And the backend server redirects to the API server to request the data.
from requests import request
from app.core.config import cnf
class CreateHTTPRequest:
def __init__(self):
self.base_url = cnf.API_SERVER_HOST
self.headers = {
cnf.API_KEY_NAME: cnf.API_KEY,
'Content-Type': 'application/json;charset=utf-8'
}
def get(self, path, params=None):
url = self.base_url + path
response = request("GET",url, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
def post(self, path, data=None, params=None):
url = self.base_url + path
response = request("POST", url, data=data, headers=self.headers, params=params)
response.raise_for_status()
return response.json()
I don't understand what is it that I'm doing wrong here. Initially, CORS blocked everything (including GET requests), but after I enabled CORS(app)
, I started to get response for the GET requests. It still doesn't work for the POST request even though all origins are allowed. How can I fix this and what am I overlooking?
ERROR
Access to XMLHttpRequest at 'http://api-server/group-classifier/' (redirected from 'https://backend-server/group-classifier') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
POST http://backend-server/group-classifier/ net::ERR_FAILED