Search code examples
corsvercelmongodb-atlasflask-cors

Blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Error in my FLASK app server


I am trying to fetch data from a flask server that I created, but it seems to give me the CORS error and is not working.

@app.route('/api/data', methods=['GET', 'OPTIONS'])
def get_data():
    if request.method == 'OPTIONS':
        response = jsonify()
    else:
        articles = db.articles.find({}, {"_id": 0})
        articles_list = list(articles)
        response = jsonify(articles_list)
    
    response.headers.add('Access-Control-Allow-Origin', 'website link')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    response.headers.add('Access-Control-Allow-Methods', 'GET')
    return response

This is the part where I want to fetch the data, and the endpoint is working perfectly when I try fetching it with POSTMAN, but gives error while trying to display it on my frontend.

It gives me the error:

Access to fetch at 'server/api/data' from origin 'website' 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 even have the cors allowed.

app = Flask(__name__)
CORS(app)

It is hosted on vercel, and it was working fine, but suddenly stopped working.


Solution

  • Hey so I got this to work, so am sharing what I did . Now my problem was that while hosting it through vercel, there was a issue that my API was giving a CORS error while fetching the data. It was working perfectly in my local machine but the moment I hosted it, it was showing an issue. Further there was the fact that the Content-type showed wrong when hosted.

    For example, when checking it through postman.. the headers while running on local host were -

    Content-Type : application/json

    but the moment I hosted it on vercel and ran the api, it came as -
    Content-Type : text/plan; charset=utf8

    I tried fixing this by explicitly setting the content type as application/json but it still came out to be the same. Now to fix this issue, I updated the file structure. My python file was called newsic-api.py and it was inside the api folder, so my vercel.json file was

    {
      "rewrites": [
        { "source": "/(.*)", "destination": "/api/newsic-api" }
      ]
    }
    

    but the moment I changed the filename to index.py and made the vercel.json as

    {
      "rewrites": [
        { "source": "/(.*)", "destination": "/api/index" }
      ]
    }
    

    it started to work perfectly. Hope it helps to anyone who faces the same issue!!