简体   繁体   中英

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 www.example.com and do a fetch() call in java script I am getting CORS error

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM