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>