0

I am writing a Flask POST request handler to add a CLIENT.

app = Flask(__name__)
CORS(app)


@app.post("/api/clients/")
def addClient():
    data = open('./src/clients.json', 'w+')
    clients = json.load(data)
    req = json.loads(request.data)
    clients.append(req)
    json.dump(clients, data)
    data.close()
    return req

But when I execute this Javascipt fetch() API in browser:

let u = "http://url/api/clients/n1/"
let b = {
  "client": "n1",
  "details": {
    "address1": "Line1",
    "address2": "line2",
    "city": "city",
    "email": "@",
    "gst": "gstno"
  }
}

const addStudent = async (us, c) => {
const response = await fetch(us, {
    method: "POST",
    headers: {
    "Content-Type": "application/json",
    },
    body: c,
});

const data = await response.json();

console.log(data);
};

addStudent(u, b);

The browser console gives the following error:

Access to fetch at 'url/api/clients/' from origin 'null' 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.

For reference, these are the errors mentioned on the Flask command line.

127.0.0.1 - - [26/Mar/2023 18:09:05] "POST /api/clients/ HTTP/1.1" 500 - Traceback (most recent call last): File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask\app.py", line 2551, in call return self.wsgi_app(environ, start_response) File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask\app.py", line 2531, in wsgi_app response = self.handle_exception(e) File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs))) File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask\app.py", line 2528, in wsgi_app response = self.full_dispatch_request() File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask\app.py", line 1825, in full_dispatch_request rv = self.handle_user_exception(e) File "E:\All_Codes\WEB_DEV\excel-o-meter\venv\lib\site-packages\flask_cors\extension.py", line 165, in wrapped_function return cors_after_request(app.make_response(f(*args, **kwargs)))

Do I have to add any specific header as mentioned or I have some ERROR at my Flask end?? The lst line in the command line seems to give me the CORS error.

ahmedzzyy
  • 25
  • 1
  • 6

1 Answers1

1

Can you please try this and check?

Method 1

Install flask-cors

pip install -U flask-cors

then after app initialization, initialize flask-cors with default arguments:

 from flask import Flask
 from flask_cors import CORS 

 app = Flask(__name__)
 CORS(app)

 @app.route("/")
 def helloWorld():
  return "Hello, cross-origin-world!"

UPDATE

Method 2

If you don't want to use any additional package you could also do something like this

 @app.route('your own route', methods=['GET'])
 def yourMethod(params):
   response = flask.jsonify({'somekey': 'somevalue'})
   # Note : Ideally '*' should be replaced with your host origin
   response.headers.add('Access-Control-Allow-Origin', '*') 
   return response

I would recommend please try using following code to define your endpoint

@app.route("/api/clients/", methods=['POST'])

instead of

@app.post("/api/clients/")

Reference link - Flask http methods

inkredusk
  • 919
  • 4
  • 16
  • What does this do? Enables CORS?? – ahmedzzyy Mar 26 '23 at 11:39
  • Yes. It will enable cors – inkredusk Mar 26 '23 at 11:42
  • I have updated my answer. The first method uses an additional package for enabling cors. If you don't want to use the same you can check method 2 – inkredusk Mar 26 '23 at 11:49
  • 1
    @ahmedzzyy: this is a separate issue. i would suggest either you ask a separate question for this or please refer this link https://stackoverflow.com/questions/21689364/method-not-allowed-flask-error-405 . Also if my answer has helped you please do accept the same – inkredusk Mar 26 '23 at 12:22
  • I have edited the question with the new but highly similar error I m getting. – ahmedzzyy Mar 26 '23 at 12:41