Python flask cors failing for POST but passing for GET


I have created a backend api using python flask and hosted on gcp compute engine.

When I try to access the api using a website and do a fetch() call in java script I am getting CORS error

Access to fetch at 'https://{ip}/api' from origin '' 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.

When I do a GET call thats working but my POST call isnt working and gives the above error

Below is the POST call which is failing

@app.route('/api/v1/xxx', methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type'])
def upload_file():
    #some code
        return "successfully"

and below is the working get call

@app.route('/api/v1/xxx', methods=['GET'])
@cross_origin(origin='localhost',headers=['Content- Type'])
def signUpCheck():
    #some code
    return jsonify(fun())


I found the answer to my solution,
so what was happening was I routed all calls via nginx and hence on server side I only received options call and nothing else.
When I tried to call the API via postman and not javascript I received file size exception. I had to add below line in my nginx file to get this resolved

client_max_body_size 100M;

In general you will get cors error if there is something wrong on server side so do try your api call via postman as well

Answered By – Legendary_Hunter

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published