Home  >  Q&A  >  body text

Solving problems with POST requests in Flask and Python

<p>I'm writing a Flask POST request handler to add a CLIENT. </p> <pre class="brush:php;toolbar:false;">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</pre> <p>But when I execute this Javascript's <code>fetch()</code> API in the browser: </p> <pre class="brush:php;toolbar:false;">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);</pre> <p>The browser console displays the following error: </p> <blockquote> <p> Access fetch to 'url/api/clients/' is blocked because origin 'null' does not have an 'Access-Control-Allow-Origin' header. If an opaque response meets your needs, set the request's mode to 'no-cors' to disable CORS fetching the resource.</p> </blockquote> <p>For reference, these are the errors mentioned in the Flask command line: </p> <blockquote> <p>127.0.0.1 - - [March 26, 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, <strong>Call</strong> return self.wsgi_app(environment, 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)))</p> </blockquote> <p><strong>Do I need to add a specific header as mentioned above, or am I having some bug on the Flask side? </strong> The last line in the command line seems to give a CORS error. </p>
P粉476475551P粉476475551413 days ago530

reply all(1)I'll reply

  • P粉459578805

    P粉4595788052023-09-03 12:52:58

    Can you try it and check it out?

    method 1

    Install flask-cors

    pip install -U flask-cors

    Then after the application is initialized, initialize flask-cors with default parameters:

    from flask import Flask
     from flask_cors import CORS 
    
     app = Flask(__name__)
     CORS(app)
    
     @app.route("/")
     def helloWorld():
      return "Hello, cross-origin-world!"

    renew

    Method 2

    You can also do this if you don't want to use any additional packages

    @app.route('your own route', methods=['GET'])
     def yourMethod(params):
       response = flask.jsonify({'somekey': 'somevalue'})
       # 注意:理想情况下,'*' 应该被替换为你的主机来源
       response.headers.add('Access-Control-Allow-Origin', '*') 
       return response

    I suggest please try using the following code to define your endpoint

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

    instead of

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

    Reference link - Flask http methods

    reply
    0
  • Cancelreply