Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Python Flask app: CORS error despite using Flask-CORS

I'm facing a CORS-related problem with my Python Flask application, and despite my efforts, I haven't been able to resolve it. I'd appreciate any guidance or suggestions to help me overcome this hurdle.

Problem: I have a simple Flask app that serves as an API for my frontend. However, when trying to make requests from my frontend (running on a different domain), I encounter CORS issues. I've already installed the Flask-CORS extension to handle this, but it doesn't seem to be working as expected.

Code:

Here's a simplified version of my Flask app:

from flask import Flask, jsonify
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/api/data', methods=['GET'])
def get_data():
    data = {'message': 'Hello, CORS!'}
    return jsonify(data)

if __name__ == '__main__':
    app.run(debug=True)

And here's a snippet from my frontend making a request:

fetch('http://localhost:5000/api/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

What I've Tried:

  1. Installed Flask-CORS using 'pip install flask-cors'.
  2. Imported and initialized CORS in my Flask app as shown in the code above.
  3. Verified that the 'Access-Control-Allow-Origin' header is present in the response.
  4. Tried different variations of CORS configurations, such as specifying origins explicitly or using the wildcard ('*') for all origins.

Despite these efforts, I'm still facing CORS issues. Any insights into what might be going wrong or suggestions on how to debug this would be greatly appreciated. Thank you!

like image 918
Elen Miroyan Avatar asked Dec 29 '25 06:12

Elen Miroyan


1 Answers

In case you're on a Mac just change the port of the application, I did some research and seams like the port 5000 is used in one of Apple's services. On my case I just changed to 5050 and worked normally.

like image 72
Gabriel Corrêa Avatar answered Dec 30 '25 22:12

Gabriel Corrêa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!