Flask API deployed, having CORS issue: getting " No 'Access-Control-Allow-Origin' header is present on the requested resource."

My flask API has been deployed and I can access the endpoints from the browser or command line without issues and the data is returned. However when I try to access the data from my react front-end locally, I am still getting the following error:

Access to fetch at 'https://website-v2-backend.onrender.com/weo/countries' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I’ve configured my app to add these headers using the @app.after_request decorator like so:

app = create_app()
cors = CORS(app, resources={r"/*": {"origins": "*"}})

@app.after_request
def add_cors_headers(response):
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    return response

However, when I try to access the API, those headers are not present. here is the response from entering curl -I https://website-v2-backend.onrender.com/weo/countries :

HTTP/2 200
date: Sat, 11 Mar 2023 17:16:14 GMT
content-type: application/json
cf-ray: 7a6571affb898413-YVR
vary: Accept-Encoding
cf-cache-status: DYNAMIC
x-render-origin-server: gunicorn
server: cloudflare
alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400

No Access-Control-Allow- headers are there. Are they getting stripped by Render? How can I make sure they’re accessible by my front end?

1 Like

Hi,

I’ve replied to the ticket you also opened, let’s keep the conversation there for now.

However, this does appear to be a code issue and not a Render issue.

Alan

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.